Advanced·6 min·advanced · oop
Dataclasses
Dataclasses
@dataclass auto-generates __init__, __repr__, and __eq__ from your annotated fields. Modern Python's answer to "a class that just holds data."
Two things to remember
- Use
field(default_factory=list)for mutable defaults (never= []!). - Add
frozen=Trueto make instances immutable (hashable, dict-key safe).
Versus namedtuple / dict
- More readable than dicts (you get attributes, not string lookups)
- More flexible than namedtuple (mutable by default, supports inheritance)
- Less ceremony than a hand-written class
Try it
- Make
Taskfrozen and put one in aset. - Add a
due: datetime | None = Nonefield.