@dataclass (Python 3.7+) auto-generates boilerplate like __init__, __repr__, and __eq__ for classes whose main job is holding data.
The Problem Dataclasses Solve
# Without dataclass: lots of repetitive boilerplateclass Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return f"Point(x={self.x}, y={self.y})" def __eq__(self, other): return isinstance(other, Point) and self.x == other.x and self.y == other.y
# With dataclass: same result, far less codefrom dataclasses import dataclass@dataclassclass Point: x: int y: intp1 = Point(1, 2)p2 = Point(1, 2)print(p1) # Point(x=1, y=2), __repr__ auto-generatedp1 == p2 # True, __eq__ auto-generated (compares field by field)
Default Values
from dataclasses import dataclass, field@dataclassclass User: name: str age: int = 18 # simple default tags: list = field(default_factory=list) # mutable default, MUST use default_factoryu = User("Bob")u.age # 18u.tags # []
Never use a mutable literal as a dataclass default
@dataclassclass User: tags: list = [] # ValueError! dataclass explicitly forbids this
This is the dataclass equivalent of the mutable default argument trap (see Common-Pitfalls). Use field(default_factory=list) instead, which creates a fresh list per instance.
frozen=True: Immutable Dataclasses
@dataclass(frozen=True)class Point: x: int y: intp = Point(1, 2)p.x = 99 # FrozenInstanceError, cannot modify after creation
Frozen dataclasses with only hashable fields are automatically hashable, usable as dict keys or set members.
Ordering
@dataclass(order=True)class Version: major: int minor: int patch: intVersion(1, 2, 0) < Version(1, 3, 0) # True, compares field by field in declaration order
All fields with defaults must come AFTER fields without defaults, across the ENTIRE inheritance chain combined. This can force you to give every field in a subclass a default if the parent has any defaulted field.
Reach for @dataclass any time you catch yourself writing a class that is mostly __init__ assigning parameters to self. It removes the boilerplate while keeping full class capabilities (methods, inheritance, etc).