Dataclasses
A dataclass is a class that gets __init__, __repr__, and optional comparison methods generated from type-annotated fields. @dataclass is the decorator that writes that boilerplate.
Detailed Explanation
The class that only stores sku, qty, and cents used to cost twenty lines of __init__ and __repr__. dataclasses (3.7+) writes those lines from the field list:
@dataclass
class Order:
sku: str
qty: int = 1
The decorator reads the annotations, builds __init__(self, sku: str, qty: int = 1), a repr, and, if you ask, __eq__ and ordering. Fields with defaults must follow fields without, the same as function parameters.
frozen=True makes instances roughly immutable: assigning order.qty = 2 raises FrozenInstanceError. Frozen dataclasses can be hashable if every field is hashable, so they can be dict keys. slots=True (3.10+) generates __slots__ and drops __dict__, saving memory.
field(default_factory=list) is the safe mutable default. field(repr=False) hides secrets from the repr. field(compare=False) excludes a field from equality. field(init=False) is set in __post_init__, which runs after the generated __init__.
Dataclasses are still classes. You can add methods. Inheritance works; subclass fields append to the parent. A frozen parent plus a mutable child is allowed and confusing — keep mutability consistent down the tree.
They are not a validation library. An annotation of int does not coerce or reject a string. Use Pydantic, attrs with converters, or hand-written checks in __post_init__ when the data comes from the outside.
Prefer a dataclass over a dict when the shape is stable and you want attribute access and a repr. Prefer a TypedDict when the value must stay a dict. Prefer a NamedTuple when you want tuple unpacking and a tiny immutable record. Prefer a full class when construction is complicated or identity is not "these fields".
Code Examples
from dataclasses import dataclass, field
@dataclass
class Order:
sku: str
qty: int = 1
tags: list[str] = field(default_factory=list)
def label(self) -> str:
return f"{self.qty}×{self.sku}"
line = Order("A-1", 2)
line.tags.append("fragile")
print(line) # Order(sku='A-1', qty=2, tags=['fragile'])
print(line == Order("A-1", 2, ["fragile"])) # True@dataclass(frozen=True, slots=True)
class Money:
cents: int
currency: str = "USD"
price = Money(2500)
print(price.cents) # 2500
# price.cents = 0 # dataclasses.FrozenInstanceError@dataclass
class Cart:
items: list[str] = field(default_factory=list)
size: int = field(init=False)
def __post_init__(self) -> None:
self.size = len(self.items)Common Gotchas
Not a validator
`Order(sku=12, qty="x")` still constructs. Check at the boundary.
Mutable fields make `frozen=True` hashable objects unsafe if you mutate the list inside
freeze the whole graph or use tuples.
`eq=True` (the default) compares by fields
two instances with the same fields are equal even if they are not the same object. That is usually what you want.