You’ll be able to
- Replace boilerplate
__init__with@dataclass - Add default values and default factories to dataclass fields
- Get free
__repr__,__eq__, and comparison methods - Choose between
frozen=True(immutable) and mutable dataclasses
Loading lesson…
Why this matters
FastAPI request models, Pydantic v1 internals, and half of modern config layers use @dataclass or its stricter cousin attrs to kill boilerplate. Staff engineers reach for frozen=True + slots=True when they need hashable, memory-lean value objects for caching keys or event payloads.
Common pitfalls
- Using a mutable default like
field=[]— raisesValueError; usefield(default_factory=list)instead. - Assuming
frozen=Truemeans deeply immutable — nested lists still mutate; wrap in tuples or useMappingProxyType. - Skipping
slots=Trueon hot-path classes — costs ~40% more memory per instance versus a slotted dataclass.