Dataclasses
The boilerplate problem
Section titled “The boilerplate problem”A class that holds data typically needs __init__, __repr__, and __eq__ — all written by hand with identical logic: copy constructor arguments into self.attr, format attributes into a string, compare attribute by attribute.
@dataclass generates all of this from the class-level type annotations.
from dataclasses import dataclass
@dataclassclass Point: x: float y: floatPython generates:
__init__(self, x: float, y: float)that setsself.xandself.y__repr__that returns"Point(x=1.0, y=2.0)"__eq__that compares all fields
Default values
Section titled “Default values”Scalar defaults work like keyword arguments:
@dataclassclass Config: host: str = "localhost" port: int = 8080 debug: bool = Falsefield() for mutable defaults
Section titled “field() for mutable defaults”You cannot use a mutable object (list, dict) directly as a default — Python would share one instance across all objects.
Use field(default_factory=...) instead:
from dataclasses import dataclass, field
@dataclassclass Inventory: name: str tags: list = field(default_factory=list) quantity: int = 0field also accepts:
| Parameter | Effect |
|---|---|
default_factory | Called with no arguments to produce each instance’s default |
repr=False | Exclude the field from __repr__ |
compare=False | Exclude the field from __eq__ and __lt__ |
init=False | Exclude from __init__; set manually in __post_init__ |
frozen=True — immutable records
Section titled “frozen=True — immutable records”frozen=True makes the dataclass immutable: it generates __setattr__ and __delattr__ that raise FrozenInstanceError, and it also generates __hash__ so frozen instances can be used as dict keys or in sets.
@dataclass(frozen=True)class Color: red: int green: int blue: intAdding custom methods
Section titled “Adding custom methods”A dataclass is still a normal class — add any methods you need:
@dataclassclass Point: x: float y: float
def distance_from_origin(self) -> float: return (self.x ** 2 + self.y ** 2) ** 0.5Full runnable demo
Section titled “Full runnable demo”from dataclasses import dataclass, field
@dataclassclass Point: x: float y: float
def distance_from_origin(self) -> float: return (self.x ** 2 + self.y ** 2) ** 0.5
@dataclassclass Inventory: name: str tags: list = field(default_factory=list) quantity: int = 0
def add_tag(self, tag: str) -> None: self.tags.append(tag)
@dataclass(frozen=True)class Color: red: int green: int blue: int
p = Point(3.0, 4.0)print(p)print(p.distance_from_origin())
item = Inventory("Widget")item.add_tag("sale")item.add_tag("clearance")print(item)
red = Color(255, 0, 0)print(red)print(red == Color(255, 0, 0))Loading Python runtime (first run only)…