Sub topic 12
Less boilerplate with dataclasses
This chapter assumes you can write a class with __init__, know what __repr__ and __eq__ do, and understand that a mutable class attribute is shared by every instance. Earlier chapters covered all of these.
The problem dataclasses solve
A class that only holds data needs the same three methods every time: __init__ to store fields, __repr__ to print readably, and __eq__ to compare by value. Writing them by hand is repetitive, and the three can drift out of sync when you add a field.
The @dataclass decorator reads the class's annotated fields and generates those methods for you.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
paid: bool = False
o = Order(1)
o.items.append("book")
print(o) # Order(order_id=1, items=['book'], paid=False)
print(Order(1) == Order(1)) # TrueOnly annotated names become fields. The annotation is not enforced at runtime, so Order("abc") runs without error. The annotations serve readers and type checkers.
What gets generated
By default, @dataclass creates:
__init__, with one parameter per field, in the order you declared them.__repr__, showing the class name and each field.__eq__, which compares the fields as tuples. It returnsNotImplementedif the other object is of a different class.
Defaults and mutable fields
A field with a default value must come after all fields without one, the same rule as for function parameters.
Mutable defaults need care. This is the shared-class-attribute bug from earlier, and dataclasses refuse to let it happen silently:
from dataclasses import dataclass
try:
@dataclass
class Bad:
items: list[str] = []
except ValueError as exc:
print(exc) # mutable default <class 'list'> for field items is not allowed: use default_factoryUse field(default_factory=list) instead. The factory is a function called once for each new instance, so every instance gets its own list.
Common options
You pass options to the decorator.
| Option | Effect |
|---|---|
| `frozen=True` | Assigning to a field raises `FrozenInstanceError`. Also makes instances hashable. |
| `order=True` | Generates `<`, `<=`, `>`, `>=`, comparing fields in order. |
| `slots=True` | Generates `__slots__` (Python 3.10+), saving memory per instance. |
| `kw_only=True` | Makes every parameter keyword-only (Python 3.10+). |
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
print(Version(1, 2) < Version(1, 10)) # True
print({Version(1, 0): "first"}) # {Version(major=1, minor=0): 'first'}
v = Version(1, 0)
try:
v.major = 2
except AttributeError as exc:
print(type(exc).__name__) # FrozenInstanceErrorFrozenInstanceError is a subclass of AttributeError, so the except clause catches it.
Computed fields with `__post_init__`
The generated __init__ calls __post_init__ after storing the fields, if you define it. Use it for validation or derived values. Mark derived fields with init=False so they are not constructor parameters.
from dataclasses import dataclass, field
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width <= 0 or self.height <= 0:
raise ValueError("sides must be positive")
self.area = self.width * self.height
print(Rectangle(3, 4)) # Rectangle(width=3, height=4, area=12)Note that area goes stale if you later change width. For values that must always match the other fields, a property is the better tool.
Flow of construction
Common mistakes
- Writing
items: list = []and expecting it to work. Usedefault_factory. - Omitting the annotation.
count = 0in the class body is a plain class attribute, not a field. - Expecting type checks at runtime. Use a validation step in
__post_init__if you need one. - Using
frozen=Trueand then trying to set derived values in__post_init__. Useobject.__setattr__(self, "name", value)there, or compute the value in a property.
Exercise
Write a dataclass Point with integer fields x and y that can be used as a dictionary key and whose instances cannot be changed after creation. What happens if you leave out the option that makes it hashable?
Show answer
Use @dataclass(frozen=True) on class Point: x: int; y: int (written on separate lines). With frozen=True and the default eq=True, dataclass generates __hash__ from the fields, so {Point(1, 2): "a"} works and p.x = 5 raises FrozenInstanceError. With plain @dataclass, __eq__ is generated and __hash__ is set to None, so using a Point as a key raises TypeError: unhashable type: 'Point'.