Full answer
python
from dataclasses import dataclass, field, asdict, replace
@dataclass
class Order:
id: int
items: list[str] = field(default_factory=list)
paid: bool = False
@dataclass(frozen=True, order=True)
class Money:
amount_paise: int
currency: str = "INR"
o = Order(1); o.items.append("pen")
print(o, Order(2).items, o == Order(1, ["pen"]))
m = Money(4550)
try:
m.amount_paise = 1
except Exception as e:
print(type(e).__name__)
print(replace(m, amount_paise=100), sorted([Money(300), Money(100)])[0], {m: "ok"}[Money(4550)])
print(asdict(o))Output:
text
Order(id=1, items=['pen'], paid=False) [] True
FrozenInstanceError
Money(amount_paise=100, currency='INR') Money(amount_paise=100, currency='INR') ok
{'id': 1, 'items': ['pen'], 'paid': False}Each Order gets its own list because default_factory runs per instance; writing items: list = [] raises a ValueError at class creation, which protects against the shared-default bug. The frozen Money rejects assignment with FrozenInstanceError, can be a dict key, and order=True adds comparisons field by field. replace creates a modified copy, the usual way to 'change' a frozen object, and asdict converts to plain dicts for JSON. Add slots=True (Python 3.10+) to save memory for many instances.
python
from dataclasses import dataclass, field, asdict, replace
@dataclass
class Order:
id: int
items: list[str] = field(default_factory=list)
paid: bool = False
@dataclass(frozen=True, order=True)
class Money:
amount_paise: int
currency: str = "INR"
o = Order(1); o.items.append("pen")
print(o, Order(2).items, o == Order(1, ["pen"]))
m = Money(4550)
try:
m.amount_paise = 1
except Exception as e:
print(type(e).__name__)
print(replace(m, amount_paise=100), sorted([Money(300), Money(100)])[0], {m: "ok"}[Money(4550)])
print(asdict(o))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Generates __init__, __repr__, __eq__
- default_factory for mutable defaults
- frozen=True for value objects
- replace makes modified copies
- slots=True saves memory
Common mistakes
- Using a mutable default directly
- Mutating frozen instances through nested lists
Follow-ups
- How does a dataclass compare with Pydantic models?
- What does __post_init__ do?
Tips
- Mention default_factory