Module 17 · Advanced Python Concepts — topic 13 of 14
Dataclasses
Concise data-holding classes with @dataclass: automatic __init__, __repr__ and __eq__, default values and default_factory, ordering, frozen instances, __post_init__ validation, computed fields, asdict and replace.
Learning objectives
- Define dataclasses with defaults
- Use options such as order and frozen
- Validate and compute fields in __post_init__
Definition
The @dataclass decorator generates common methods for classes that mainly store data, based on their annotated fields: __init__, __repr__, __eq__ and optionally ordering and immutability.
Introduction
A Point class with __init__, __repr__ and __eq__ takes a dozen lines. With @dataclass it takes three.
Why it matters
Dataclasses remove boilerplate, prevent mistakes in hand-written equality and repr methods, and make data models obvious at a glance.
Detailed explanation
Decorate a class with @dataclass and declare fields with annotations: x: float. Fields with defaults must come after fields without.
Generated __init__ takes the fields in order; __repr__ shows them; __eq__ compares them.
Mutable defaults need field(default_factory=list) so each instance gets its own list.
@dataclass(order=True) adds <, <=, >, >= comparing fields in order; frozen=True makes instances immutable (and hashable).
__post_init__ runs after the generated __init__, ideal for validation and computing derived fields declared with field(init=False).
dataclasses.asdict converts an instance (recursively) to a dictionary; replace creates a modified copy.
slots=True (Python 3.10+) adds __slots__ for lower memory use.
kw_only=True makes every field keyword-only, so calls such as Order(id=1, discount=0.1) stay readable and can't silently swap two arguments of the same type.
field(repr=False) hides a field (such as a password hash) from the generated repr, and field(compare=False) excludes it from equality and ordering.
Compared with namedtuple, dataclasses are mutable by default, support defaults and methods naturally, and validate in __post_init__; compared with a hand-written class, they remove boilerplate without hiding any behaviour.
Syntax
- Fields come from annotations.
- default_factory for mutable defaults.
- order and frozen options.
Code examples
A first dataclass
Point(x=3, y=4) True Point(x=1, y=0.0)
Ordering, frozen and default_factory
[Version(major=1, minor=9), Version(major=2, minor=0), Version(major=2, minor=1)] FrozenInstanceError Cart(items=['pen']) Cart(items=[])
More examples
Validation and computed fields
1134.0
('pen', 20.0, 3)
2 1260.0
discount must be between 0 and 0.5Step-by-step explanation
- total is not an __init__ argument; __post_init__ computes it after validating the discount.
- asdict turns the order into plain data, ready for JSON.
- replace builds a new order, running __init__ and __post_init__ again, so the total is recalculated.
Expected output
Running “Validation and computed fields” prints exactly:
Practical applications
- Configuration objects and API response models.
- Records read from CSV files.
Best practices
- Use dataclasses for data-centred classes.
- Validate in __post_init__.
- Use frozen=True for value objects.
Common mistakes
Mutable default value
Avoid
Prefer
dataclasses reject plain mutable defaults with ValueError.
Important notes
- Dataclasses are ordinary classes: you can add methods and properties.
Key takeaways
- @dataclass generates __init__, __repr__ and __eq__.
- default_factory, order and frozen customise it.
- __post_init__ validates and computes.
Try it yourself
- 1Write a frozen Money dataclass with amount and currency and an add method that checks currencies.
- 2Convert a list of Student dataclasses to JSON using asdict.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?