~/learn/Python · Classes & structure
Dataclasses and type hints
Records without the boilerplate.
why this matters
Most classes just hold a few fields. Dataclasses give you the constructor, printing and comparison for free.
@dataclass writes __init__, __repr__ and __eq__ for you from annotated fields — ideal for the record-shaped objects that fill data code.
Try it: Add a units field defaulting to 1 and use it in a revenue property.
Mutable defaults need field(default_factory=list) — sharing one list across every instance is a notorious bug.
Type hints do not change runtime behaviour, but they document intent and let editors and type checkers catch mistakes early.
Pro tip
@dataclass writes __init__, __repr__ and __eq__ for you, so two records with the same values compare equal.
Common gotcha
Never use a mutable default like items: list = []. Use field(default_factory=list) instead, or every instance shares one list.
key takeaways
- @dataclass removes constructor boilerplate.
- Type hints document each field.
- Use default_factory for lists and dicts.
check your understanding
What is wrong with `tags: list = []` inside a dataclass?
free practice
Build confidence with a question you can solve without Pro.