What are Python dataclasses and how do they compare to Pydantic models?medium

Type
conceptual
Topic
dataclasses
Frequency
common
Tags
dataclasses, pydantic, OOP, type hints
Answer

@dataclass auto-generates __init__, __repr__, and __eq__ from annotated class fields, eliminating boilerplate for data-holding classes. Unlike Pydantic's BaseModel, dataclasses have no runtime type validation — they trust type hints at face value.

Explanation

field(default_factory=list) correctly solves the mutable default argument problem — each instance gets its own fresh list. frozen=True makes instances immutable and hashable, usable as dict keys or in sets. order=True auto-generates comparison methods for sorting. Pydantic adds runtime validation and serialization at the cost of some overhead — use Pydantic for API schemas, dataclasses for internal data transfer objects where speed matters. __post_init__ runs after the generated __init__ for custom setup logic.

Follow-upWhen would you choose a dataclass over a Pydantic model?
Follow-upWhat does frozen=True do to a dataclass?
Follow-upHow do you handle mutable defaults in a dataclass?