Dataclasses and typed interfaces
3.15.2
Model structured values and communicate the expected types at a function boundary.
On this page
Represent a record with a dataclass
@dataclass can generate methods such as __init__, __repr__, and __eq__ from annotated fields. Use field(default_factory=list) to create a fresh list for each record. Add explicit validation when invalid inputs are possible.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
first, second = Order(1), Order(2)
first.items.append("Tea")
print(first.items, second.items)
Example output
['Tea'] []
Make optional values explicit
Type hints describe the intended values for tools and readers. str | None says the value can be text or None. Python generally does not enforce function annotations at runtime, so validate inputs from files, APIs, and users.
def normalize(name: str | None) -> str:
return name.strip() if name is not None else "Unknown"
print(normalize(" Tea "), normalize(None))
Example output
Tea Unknown