@dataclass generates init, repr, and eq from class annotations
A dataclass is a normal class that the @dataclass decorator augments by reading annotations and generating boilerplate methods. By default it generates init, repr, and eq. With frozen=True it also generates hash and makes instances immutable. With order=True it generates comparison methods. Fields can be customized with field(), which supports default_factory, repr=False, and comparison flags. The result is concise, readable value objects with correct semantics. The trade-offs are that generated init can be awkward with complex validation, and that dataclasses are mutable by default, so hashability requires an explicit choice.
@dataclass(eq=True, frozen=True) is the standard pattern for immutable value objects that need to be hashable.
@dataclass(order=True) generates ordering based on field order; be explicit about the field order.
field(default_factory=list) is required for mutable defaults. Using a list directly raises ValueError in 3.11+.
Trade-off: dataclasses generate methods you cannot easily customize per field. For complex validation or serialization, use Pydantic or attrs.
Common mistake: assuming dataclasses are immutable. They are mutable unless frozen=True.
Common mistake: defining a field with a mutable default and sharing it across instances.
Version note: dataclasses landed in 3.7. slots=True arrived in 3.10, kw_only in 3.10, and 3.11 added stricter mutable-default checks and improved error messages.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience