Objects that protect a model
Use classes for related state and behaviour, without overengineering.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 10 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Define instance state
- Use a dataclass for records
- Avoid shared mutable class attributes
Group state with its rules
A class describes a kind of object. Each instance is one object with its own state; methods describe operations that use that state.
Understand first
Use a class when state and the operations that change it form one clear idea, such as a counter or a reservation. You already need functions, assignment and attribute access. A pair of functions with plain data is often enough for a one-off calculation.
Words you will see
- Instance
- One object created by calling a class.
- self
- The conventional name for the instance receiving a method call.
- __init__
- An initializer called on a newly created instance to establish its state.
Read the receiver
class Counter starts a class body. def add(self, amount) defines a function that becomes an instance method when accessed through a counter. first.add(3) supplies first as self and 3 as amount. You do not pass first a second time.
The initializer assigns self.value on each newly created object. Counter() uses the default zero, while Counter(10) starts another object's value at ten. The default here is an immutable number, not a shared mutable list.
State follows the object
first.add(3) reads first.value, adds three, and stores the result back on first. second.value is untouched because second is a different object. Assigning alias = first would make two names for the same counter; it would not copy state.
This counter deliberately accepts ordinary numeric additions; it does not promise a nonnegative invariant. Add validation if the domain requires one. For just sum(values), a class would add ceremony without adding a useful boundary. Core recap: choose objects for a coherent stateful role, not just to group unrelated functions.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
self.value = valueSet an attribute on the new receiver.
first = Counter()Initialize the first counter to zero.
second = Counter(10)Create an independent counter starting at ten.
first.add(3)Only the first receiver becomes three.
A class is useful when operations belong to a coherent stateful concept. Functions plus data are often enough; adding a class is not automatically better design. Instance attributes belong to each object.
Conceptual receiver and ownership diagram, not a live memory trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Constructfirst → Counter(value=0); second → a different Counter(value=10).
- Bindfirst.add(3) binds self to first, so the method reads first.value.
- WriteOnly first.value is rebound to 3; no path in this call writes second.value.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Call second.add(-2).
Try: Insert the call before print.
The output becomes 3 8; this counter has no nonnegative rule.
Make second refer to first.
Try: Replace second = Counter(10) with second = first.
Both printed values become 3 because the names now share one counter.
Before you move on
After alias = first and alias.add(2), which counter changes?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
first becomes 5 because alias refers to that same instance. second remains 10. A new name does not run __init__ or create a copy.
Data records without repeated boilerplate
A dataclass generates common record methods from annotated fields. It saves repeated code; it does not validate field types for you.
Understand first
A task is mostly named data: title and done. Use a dataclass when generated construction, readable representation and field-based equality match the record you need. Use a regular class when a different lifecycle or API is clearer.
Words you will see
- Field
- A named part of a dataclass record.
- Annotation
- A type description such as title: str; not an automatic runtime check.
- Generated method
- A method supplied by the dataclass decorator instead of handwritten code.
What the decorator supplies
@dataclass transforms Task after its class body has been created. title: str declares a required field. done: bool = False declares a field with a default. Task("Read lists") invokes generated initialization with that title and False.
By default the decorator also supplies a representation and equality based on fields between instances of the same class. Two separately created Task records may compare equal while still being different objects. It does not make the record a dictionary or a tuple.
Data is still ordinary object state
task.done = True rebinds one field on this task, so print reads Read lists and True. The string annotation does not reject Task(123); add explicit validation, perhaps __post_init__, when the model requires it.
This mutable dataclass is not hashable by default because field changes could undermine dictionary-key lookup. Do not force a hash just to put changing tasks in a set. Choose a stable identifier or a genuinely immutable value model instead. Recap: generated convenience is not a domain rule.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@dataclassGenerate record methods for the following class.
title: strDeclare the required title field.
task = Task("Read lists")Use generated initialization and the default done=False.
task.done = TrueUpdate the field before reading it for print.
A dataclass can generate initialisation, representation and equality for a record. Type annotations document intent; they do not enforce input validation at runtime.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Leave the task unfinished.
Try: Remove task.done = True.
The original print ends with False.
Check field-based equality.
Try: Append print(task == Task("Read lists", True)).
It prints True even though the right side is a new object.
Before you move on
Are Task("Read") and another Task("Read") equal and identical?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
They compare equal because their fields match, but they are not identical: two constructor calls create separate records. Editing one done field makes equality change.
Put invariants at meaningful boundaries
An invariant is a rule that must hold after every successful public operation. Validate a proposed change before writing state.
Understand first
A wallet must not spend money it does not have. Keeping the validation next to the update avoids asking every caller to remember the same rule. This example uses integer units, not a production money or floating-point accounting model.
Words you will see
- Invariant
- A condition that successful public operations preserve.
- Validation boundary
- The point where proposed input is checked before it becomes state.
- Read-only property
- An attribute-style reader without a public setter.
Establish, then preserve
The constructor rejects a negative initial balance before assigning _balance. spend rejects negative amounts and amounts larger than the current balance. Zero and spending the exact balance are allowed. The subtraction happens only after both checks pass.
The balance property exposes the value without defining balance assignment. A leading underscore means callers should leave the backing field alone; it is a convention, not a security barrier. Python code can deliberately bypass this API.
Failure must leave a meaningful state
Starting at eight, spending three leaves five. Spending nine then raises ValueError before subtraction. The narrow handler prints rejected, and the final balance is still five. Subtracting first and checking later would leave invalid state on failure.
Use a plain record if there is no transition rule to protect. Use explicit methods for actions such as spend because the action has meaning beyond changing a number. This tiny model assumes valid integer-like numeric inputs; a real API should also define bool, decimal, currency and overflow policies rather than guessing.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
wallet = Wallet(8)Establish a valid initial balance.
wallet.spend(3)Accept the change and reduce eight to five.
wallet.spend(9)Raise before writing because nine exceeds five.
print(wallet.balance)The rejected attempt did not undo the earlier successful spend.
If a model cannot allow a negative balance, validate updates rather than expecting every caller to remember. Encapsulation expresses rules, not just a collection of getters and setters.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Spend the remaining balance.
Try: Change wallet.spend(9) to wallet.spend(5).
Only 0 is printed; the error handler is not entered.
Reject a negative amount.
Try: Change the second spend to wallet.spend(-1).
It prints rejected and 5; a negative spend must not increase the wallet.
Before you move on
What happens if the second spend is 5 rather than 9?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
It succeeds and leaves zero. There is no rejected message. The rule forbids negative balances, not empty wallets.
Where this idea earns its place
A class is useful when state and the operations preserving its rules form a coherent model. A dataclass reduces repetitive record code, but does not decide which values are valid or which references should be shared. Start with the domain contract rather than creating a hierarchy for every noun in a requirements document.
Follow the mechanism step by step
Instance attributes normally belong to each object; class attributes are shared through the class. A generated dataclass initializer assigns fields, while default_factory can create a fresh mutable value per instance. Annotation alone does not prevent construction with an unexpected runtime type.
Work through a concrete application
Model a task with a title, completion flag and tag list. Create two tasks, add a tag to one and confirm the other remains unchanged. Add validation at the appropriate construction or update boundary. If the only operation is passing fields around, retain the simple record instead of inventing a service-like method for every access.
Failure cases and misleading shortcuts
A list stored as a normal class attribute can accidentally become shared state. frozen does not recursively freeze nested objects, and a generated equality method does not automatically make every field hashable. A repr may also expose sensitive fields unless the representation contract is deliberate.
Cost, ownership and alternatives
Objects carry representation and lookup overhead; slots can restrict attributes and sometimes reduce per-instance storage, but introduce their own inheritance and tooling considerations. Choose composition for collaborating responsibilities and a protocol for required behaviour when concrete inheritance is unnecessary.
Verify the contract
Test independent mutable fields, invalid construction, equality behaviour and intended mutation rules. If objects become dictionary keys, test hash/equality stability. Test serialization at an external boundary separately rather than assuming a dataclass instance is already a validated public API payload.
Transfer question: Does a frozen dataclass containing a list become safely immutable?
No. Normal attribute rebinding is restricted, but the referenced list may still mutate. Use immutable field values or explicitly document shallow immutability. Do not rely on frozen alone to justify hashability or safe sharing.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
A task with independent tags
Create a dataclass with a fresh tags list per task. Adding a tag to a must not change b.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Build a task that owns its tags
Return a dataclass record with title, done=False and an editable tags list that is independent of every supplied list.
The contract
- title is a string; tags is a finite iterable of strings, empty by default.
- Return a dataclass instance with title unchanged, done exactly False and tags a list preserving order and repeats.
- Copy the outer tags iterable; edits to the result or a source list must not affect one another. Each call owns a fresh list.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Record and fields
from dataclasses import is_dataclass t = make_task("Read", ["a", "b"]) assert is_dataclass(t) and t.title == "Read" and t.done is False and type(t.tags) is list and t.tags == ["a", "b"] - Empty record
from dataclasses import is_dataclass t = make_task("") assert is_dataclass(t) and t.title == "" and t.done is False and type(t.tags) is list and t.tags == [] - Order and repeats
t = make_task("Code", ("b", "a", "b")) assert type(t.tags) is list and t.tags == ["b", "a", "b"] and t.title == "Code" and t.done is False - Result owns the list
source = ["a"] t = make_task("Read", source) t.tags.append("b") assert t.title == "Read" and t.done is False and type(t.tags) is list and t.tags == ["a", "b"] and source == ["a"] and t.tags is not source - Source edits stay outside
source = ["x"] t = make_task("Review", source) source.append("y") assert t.title == "Review" and t.done is False and type(t.tags) is list and t.tags == ["x"] and source == ["x", "y"] - Independent calls
a, b = make_task("A"), make_task("B") a.tags.append("x") assert a.title == "A" and b.title == "B" and a.done is False and b.done is False and type(a.tags) is list and a.tags == ["x"] and type(b.tags) is list and b.tags == [] and a.tags is not b.tags
Why are both a factory and a supplied-input copy useful?
The factory prevents a shared omitted default; list(tags) protects explicit caller inputs. The solution uses generated record methods and one outer copy, taking O(n) work and space for n tags. Strings need no deep copy.
Complete a task without changing the draft
Make a new record from an existing dataclass task. Set done=True while keeping its class and making its tags list independent.
The contract
- task is a dataclass instance with title: str, done: bool and tags: list[str], and its constructor accepts those fields.
- Return a different instance of the same class, preserving title and ordered repeated tags while setting done exactly True.
- Do not modify the source task or its list. The result must own a new tags list, including when input tags are empty.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Same record type
from dataclasses import make_dataclass Task = make_dataclass("Task", [("title", str), ("done", bool), ("tags", list)]) s = Task("Read", False, ["a"]) r = completed_copy(s) assert type(r) is Task and r is not s and r.title == "Read" and r.done is True and type(r.tags) is list and r.tags == ["a"] - Empty fields
from dataclasses import make_dataclass T = make_dataclass("T", ["title", "done", "tags"]) s = T("", False, []) r = completed_copy(s) assert type(r) is T and r.title == "" and r.done is True and type(r.tags) is list and r.tags == [] and s.done is False and r.tags is not s.tags - Repeated tags
from dataclasses import make_dataclass T = make_dataclass("T", ["title", "done", "tags"]) s = T("X", False, ["b", "a", "b"]) r = completed_copy(s) assert type(r) is T and r.title == "X" and r.done is True and type(r.tags) is list and r.tags == ["b", "a", "b"] and s.tags == ["b", "a", "b"] - Already completed
from dataclasses import make_dataclass T = make_dataclass("T", ["title", "done", "tags"]) s = T("X", True, ["a"]) r = completed_copy(s) assert type(r) is T and r.title == "X" and r.done is True and r is not s and type(r.tags) is list and r.tags == ["a"] and r.tags is not s.tags - Result mutation isolated
from dataclasses import make_dataclass T = make_dataclass("T", ["title", "done", "tags"]) s = T("Read", False, ["a"]) r = completed_copy(s) r.tags.append("b") assert type(r) is T and r.title == "Read" and r.done is True and type(r.tags) is list and r.tags == ["a", "b"] and s.title == "Read" and s.done is False and s.tags == ["a"] - Source mutation isolated
from dataclasses import make_dataclass T = make_dataclass("T", ["title", "done", "tags"]) s = T("Read", False, ["a"]) r = completed_copy(s) s.tags.append("later") assert type(r) is T and r.title == "Read" and r.done is True and type(r.tags) is list and r.tags == ["a"] and s.tags == ["a", "later"]
Would replace(task, done=True) alone meet the contract?
No. It constructs a new record but shares the old tags reference. Copying that field makes the result independent in O(n) work and extra space for n tags; replacing the other fixed fields is constant-size work.
Transfer: make a stable plan value
The requirement changes: callers now need a frozen, hashable plan whose steps cannot grow when a source list is edited.
The contract
- title is a string and steps is a finite iterable of strings.
- Return a frozen dataclass instance with title unchanged and steps an exact tuple preserving order and repeats.
- Capture the outer sequence, do not mutate inputs, and support field-based equality and hashing. Ordinary title or steps assignment must raise FrozenInstanceError.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Frozen record fields
from dataclasses import is_dataclass p = frozen_plan("Morning", ["read", "code"]) assert is_dataclass(p) and p.__dataclass_params__.frozen and p.title == "Morning" and type(p.steps) is tuple and p.steps == ("read", "code") - Empty stable value
from dataclasses import is_dataclass p = frozen_plan("", []) assert is_dataclass(p) and p.title == "" and type(p.steps) is tuple and p.steps == () and type(hash(p)) is int - Repeats and iterator
p = frozen_plan("X", iter(["b", "a", "b"])) assert p.title == "X" and type(p.steps) is tuple and p.steps == ("b", "a", "b") and type(hash(p)) is int - Source append isolated
source = ["read"] p = frozen_plan("X", source) source.append("code") assert p.title == "X" and type(p.steps) is tuple and p.steps == ("read",) and source == ["read", "code"] and type(hash(p)) is int - Title rebinding rejected
from dataclasses import FrozenInstanceError p = frozen_plan("X", ["a"]) try: p.title = "Y" except FrozenInstanceError: pass else: assert False, "title assignment succeeded" assert p.title == "X" and type(p.steps) is tuple and p.steps == ("a",) - Equality and field protection
from dataclasses import FrozenInstanceError from dataclasses import replace p = frozen_plan("X", ["a", "a"]) q = replace(p) assert q == p and hash(q) == hash(p) and q is not p try: p.steps = () except FrozenInstanceError: pass else: assert False, "steps assignment succeeded" assert p.title == "X" and type(p.steps) is tuple and p.steps == ("a", "a")
Why does this requirement need more than the earlier fresh-list task?
The earlier task allowed local edits; this value must reject rebinding and use immutable contents. A frozen dataclass plus a tuple of strings provides that boundary. Capturing n steps costs O(n) work and space; hashing also visits the fields and tuple entries.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneClass attributes can share state
A class attribute belongs to the class. A mutable container there can be shared by every instance; a factory creates separate per-instance containers.
Understand first
Tasks may each own editable tags. An edit to one task must not leak into another. Understand the difference between creating a list now and asking for a new list whenever an instance is initialized.
Words you will see
- Class attribute
- A value stored on a class and found by instances unless their own attribute takes precedence.
- Factory
- A callable invoked to produce a fresh default value.
- Alias
- Another reference to the same object, not an independent copy.
One default recipe, many containers
field(default_factory=list) passes the list constructor itself, without parentheses. Generated initialization calls it when tags is omitted. Two calls produce distinct empty lists; appending python to first.tags therefore cannot alter second.tags.
A normal class with tags = [] in its class body instead creates one list when the class is defined. Instances can find and mutate that same list. Dataclasses reject common unhashable mutable defaults such as a direct [] and guide you toward a factory.
Defaults are not a complete copying policy
The factory protects only omitted arguments. TaggedTask("Read", supplied) retains supplied by default. If the task must own every list, copy supplied input deliberately. list(supplied) copies one level; nested objects remain shared.
Creating k task defaults takes k list allocations. Copying n supplied tags takes linear work and storage in n. Choose shared configuration at class level only when sharing is deliberate and changes have a documented owner. Recap: independent defaults and independent caller inputs are separate promises.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
tags: list[str] = field(default_factory=list)Store a recipe for a fresh default list.
first = TaggedTask("Read")Create the first default list.
second = TaggedTask("Code")Create a second list.
first.tags.append("python")Mutate just the first list.
items = [] at class level is shared by instances unless shadowed. Use self.items = [] in __init__, or field(default_factory=list) in a dataclass, for independent per-instance containers.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Pass a list explicitly to both records.
Try: Create tags = [] and pass tags as the second argument in each constructor.
Both tag displays contain python and the identity comparison becomes True.
Use an immutable default container.
Try: Change the field to tags: tuple[str, ...] = () and replace append with first.tags += ('python',).
Rebinding first.tags leaves second.tags empty. Sharing an immutable empty tuple is safe here.
Before you move on
If both records are explicitly given the same supplied list, does default_factory separate them?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The factory is skipped for an explicit argument. Copy at the ownership boundary if the contract requires independent tags.
Composition before hierarchy
Composition gives an object a collaborator. A frozen dataclass blocks ordinary field rebinding, but does not freeze objects reached through its fields.
Understand first
A study plan can contain a steps collection rather than inherit from list. This keeps plan identity separate from collection behavior. Optional depth: a frozen record is helpful for stable attributes, but its nested ownership still needs design.
Words you will see
- Composition
- Building a model from fields or collaborating objects rather than making it a subclass of them.
- Frozen dataclass
- A dataclass that rejects normal field assignment and deletion.
- Shallow protection
- A rule applied to the outer object without recursively protecting referenced objects.
Follow the reference
Plan stores the supplied steps reference. steps.append edits that same list, so plan.steps shows two strings. No assignment to plan.steps took place. frozen=True would reject plan.title = "Evening", but does not intercept list.append.
For a genuinely stable sequence of strings, convert steps to a tuple when building the plan. A tuple prevents replacing its entries, but a tuple containing a list would still expose that list's mutations. Immutability requires looking at the values, not just the outer spelling.
Choose a relationship, then an equality contract
Plan is not a kind of list. It has steps, so composition gives callers a clear boundary without promising append, pop and all other list operations on the plan itself. Inheritance is appropriate only when the child can honor the parent's contract.
Frozen records normally get field-based hashing when equality is generated, but hashing this plan raises TypeError because the steps list is unhashable. Do not assume frozen means usable as a dictionary key. Choose immutable fields or avoid hashing. Copying a list of n steps costs linear work and space; retaining it is cheaper but shares later edits.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
@dataclass(frozen=True)Protect normal assignment to fields, not every referenced object.
steps = ["read"]Create the caller-owned list.
plan = Plan("Morning", steps)Retain the same list in the record.
steps.append("practice")The shared list changes without rebinding a plan field.
Prefer collaborating small objects when inheritance would only reuse a few lines. frozen dataclasses prevent attribute rebinding but do not recursively freeze nested objects. Equality, identity and hashability still need a clear contract.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Observe a protected field assignment.
Try: Append plan.title = "Evening".
Python raises FrozenInstanceError; it does not silently retain a successful assignment.
Capture immutable steps.
Try: Pass tuple(steps) to Plan and change the annotation to tuple[str, ...].
The later source append is absent from plan.steps and the identity comparison is False.
Before you move on
Would Plan("Morning", tuple(steps)) still observe a later steps.append("review")?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No, the tuple captures the current string references in a separate container. Appending to the source list cannot add entries to that tuple.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.