Python Dataclasses vs Pydantic: Which Should You Use?
Both give you classes with typed fields and less boilerplate. The key difference: dataclasses store data, Pydantic validates and converts it.
Dataclasses
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Money:
amount: int # paise
currency: str = "INR"
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
m = Money(49900)
m == Money(49900) # True: __eq__ generated
Money("lots") # no error! type hints aren't checked at runtime
- Part of the standard library, no dependency.
- Very fast to create; ideal for internal data passed between your own functions.
frozen=Truefor immutable values,slots=Truefor lower memory use.
Pydantic
from pydantic import BaseModel, Field, EmailStr
class SignupRequest(BaseModel):
email: EmailStr
age: int = Field(ge=13)
newsletter: bool = False
req = SignupRequest.model_validate({"email": "a@b.com", "age": "21"})
req.age # 21 - the string was converted to int
SignupRequest(email="nope", age=5) # ValidationError listing both problems
req.model_dump_json() # serialise to JSON
- Validates and coerces data from untrusted sources.
- JSON parsing and serialisation built in, plus JSON Schema generation.
- Powers FastAPI request and response models.
How to choose
- Data crossing a boundary (HTTP requests, config files, environment, third-party APIs, LLM output) - Pydantic.
- Internal domain objects and value types - dataclasses.
- Pydantic can validate dataclasses too (
pydantic.dataclasses.dataclassorTypeAdapter), so you can mix both.
A common pattern: Pydantic models at the edges of your app, converted into plain dataclasses for the core business logic.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.