Lesson · Dataclasses, Enums & Data Modeling
Dataclasses
61 min readDataclasses
Dataclasses remove boilerplate for record-like classes while keeping normal class semantics. Defaults, factories, frozen instances, slots, and post-init logic let you tune the generated behavior.
Learning goals
- Explain what
@dataclassgenerates from annotated fields and what it leaves for you to write. - Use
field(default_factory=list)so each instance receives its own mutable container. - Add
__post_init__validation that rejects an emptyorder_idat construction time. - Say what
slots=Trueandfrozen=Trueeach change about instances and their attributes. - Predict the printed form of the worked example's
orderand why it includes the appended item.
Mental model
What the fence shows is the lifecycle of one class. Annotations become an __init__, field(default_factory=list) gives every Order its own items list, slots=True swaps the instance dictionary for fixed slots, and __post_init__ runs at the end of the generated __init__, which is where the empty-order_id check lives. Each option changes one stage without touching the others.
Mental model
read it top to bottom
@dataclass reads the annotated fields ↓ generates __init__, __repr__, __eq__ (order=True adds comparisons) ↓ field(default_factory=...) supplies per-instance defaults ↓ options tune the result: frozen=True, slots=True ↓ __post_init__ runs at the end of __init__ to check invariants
Core idea
A dataclass is a normal class whose boilerplate is generated from annotations: __init__, __repr__, and __eq__ come for free, and field(...) plus decorator options tune what gets generated. The worked example shows the seam where hand-written logic still belongs: default_factory=list gives each Order a fresh list, and __post_init__ runs at the end of the generated __init__, making construction the place where the order_id invariant is enforced. Everything else about the class, from extra methods to inheritance, behaves like ordinary Python.
@dataclass
@dataclass can generate initialization, representation, equality, and ordering methods from annotated fields. It does not stop the class from having normal methods and invariants.
Generated methods
A dataclass generates __init__, __repr__, and __eq__ from its annotated fields, field by field; @dataclass(order=True) adds __lt__, __le__, __gt__, and __ge__ as well. Generated methods appear only when you do not define them yourself, and field(...) options such as compare=False or repr=False keep a field out of equality or printing. The worked example leans on the generated __init__ and __repr__ while adding __post_init__ for the check the decorator cannot write.
Defaults
A default supplies a value when the constructor call omits the argument: quantity: int = 1 is stored once and reused, which is safe for immutable values. Mutable values must not be plain defaults, because every instance would share the same object; field(default_factory=...) exists for those cases. Field order matters too: fields without defaults must come before fields with defaults, or the class definition raises TypeError.
default_factory
default_factory creates a fresh default value for each dataclass instance. It is the correct tool for mutable defaults such as lists and dictionaries.
Frozen dataclasses
@dataclass(frozen=True) blocks attribute assignment after construction and, because instances no longer support mutation, generates __hash__ so instances can be dict keys and set members. Freezing is shallow: a frozen instance can still hold a list, and that list can still be appended to. The worked example is not frozen, so order.items.append("book") runs and even order.order_id = "B-2" would be allowed.
Ordering
@dataclass(order=True) generates the four comparison methods from the fields in declaration order, starting with __lt__. Equality (__eq__) exists by default, but <, <=, >, and >= are not generated without the option. When only one field should decide the order, sorted(orders, key=lambda o: o.order_id) states it more explicitly than order=True would.
Fields
field(...) configures a single field beyond its annotation: default_factory for per-instance defaults, compare=False and repr=False to keep it out of equality or printing, and init=False to leave it out of the constructor. The options sit with the field they describe, which keeps the class body readable when several fields need tuning. The worked example uses it for the one mutable field, items.
Slots
@dataclass(slots=True) replaces the per-instance __dict__ with fixed slots for the declared fields, so assigning an undeclared attribute raises AttributeError and each instance takes less memory. Slots cover exactly the fields that exist, and dynamic attributes stop working, which is the trade the option makes. The worked example sets it, so only order_id and items can be assigned on an Order.
Post-init validation
Post-init validation should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
Walkthrough
@dataclass(slots=True)reads the two annotations:order_id: stris a plain required field, anditems: list[str] = field(default_factory=list)gets its default from a callable that runs once per instance.__post_init__runs after the generated__init__has assigned the fields, soOrder("")raisesValueErrorwhileOrder("A-1")proceeds; validation happens at construction, not on first use.order.items.append("book")mutates only this instance's list; a secondOrder("A-2")gets its own empty list because the factory reruns.- Predict before running: the exact printed line
Order(order_id='A-1', items=['book']), and whatOrder("")does instead.
Experiments to try
- Create two orders and append a different item to each; confirm the factories produce separate lists and that neither order sees the other's items.
- Run
Order("")and read theValueError, then remove__post_init__and rerun; state what construction-time enforcement buys. - Replace
field(default_factory=list)with a literal= []and rerun; read theValueErrorPython raises at class creation and explain why mutable defaults are rejected. - Assign
order.extra = 1withslots=Trueand read theAttributeError; remove the option and run the same line to see the difference slots make.
Common mistakes
- Writing a mutable literal default such as
items: list[str] = []: the decorator rejects it at class creation with aValueErrorand points tofield(default_factory=list). - Using a factory that returns a shared object, for example
default_factory=lambda: shared_list: the factory runs per instance but hands back the same list, so instances still leak state into each other. - Expecting
frozen=Trueto freeze nested values: it blocks assigningorder.items, butorder.items.append(...)still mutates the list inside. - Setting
slots=Trueand then adding attributes dynamically, which raisesAttributeErrorbecause slots remove the instance dictionary.
Practice: Easy
- Run the worked example and record the printed line; then print
order.itemsand explain where the list came from. - Create two orders, append different items to each, and record both
itemslists; explain why they are not shared. - Run
Order("")and record theValueError; identify which method raised it and when that method ran.
Practice: Medium
- Add a
quantity: int = 1field and atotal()method that multiplies it bylen(self.items); verify the default and the generated__repr__both include the new field. - Write a hand-rolled class version of
Order(manual__init__,__repr__,__eq__) and compare it with the dataclass; list exactly which methods the decorator removed and what it did not do. - Add a
status: str = "open"field, then move it beforeorder_idand read theTypeError; explain the field-order rule that produces it.
Practice: Hard
- Design a frozen
Invoicedataclass with slots and ordering: alinesfield built bydefault_factory, a__post_init__check that rejects an empty invoice, and tests for equality, ordering, and a failed assignment. - Build a failure lab: a mutable literal default and the class-creation
ValueError; a factory returning a shared list that leaks between instances;frozen=Truewith a nested list that stays mutable. Explain each mechanism and the fix. - Connect this lesson to named tuples and enums: for a record with a fixed set of status values, explain which of the three tools fits the record part and which fits the status part, and why.
Lesson checklist
- I can say which methods
@dataclassgenerates and which stay hand-written, like__post_init__. - I can choose between a plain default and
field(default_factory=...)based on whether the value is mutable. - I can enforce an invariant at construction time with
__post_init__. - I can explain what
frozen=Trueandslots=Trueeach change about assignment and attributes.
Remember
A dataclass generates the record boilerplate from annotations and leaves a seam for real logic: `__post_init__` runs at the end of the generated `__init__`, and `field(default_factory=...)` gives each instance its own mutable value. The worked example's `Order` uses both, plus `slots=True`, and its printed line comes straight from the generated `__repr__`; everything a normal class can do remains available.
Interview angles
What is the main purpose of **@dataclass**?+
@dataclass can generate initialization, representation, equality, and ordering methods from annotated fields. It does not stop the class from having normal methods and invariants.
What should you pay attention to when using **Generated methods**?+
@dataclass reads annotated fields and writes __init__, __repr__, and __eq__ into the class, adding ordering methods only with order=True; anything you define yourself, such as __post_init__, extends the result. The worked example relies on the generated __repr__ for its printed line.
How does **Defaults** fit into this lesson?+
Plain defaults such as quantity: int = 1 are evaluated once and reused, so they fit immutable values; mutable defaults must come from field(default_factory=...) so the callable runs fresh per instance. The worked example's items field uses field(default_factory=list) to give every Order its own list.
Why does `@dataclass` reject `items: list[str] = []` at class creation?+
A literal list default would be created once at class definition and shared by every instance, so the decorator raises ValueError and points you to field(default_factory=list), which runs the factory per instance instead.