🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Dataclasses vs Pydantic: Modeling and Validating Data

Python DataData ModelingđŸŸĸ Free Lesson

Dataclasses vs Pydantic: Modeling and Validating Data

Every program has a point where untrusted bytes become typed objects — a JSON body arriving from a client, a row read from a CSV export, a message from a queue. The quality of that conversion decides how much of your codebase can assume its data is correct. Skip it, and every function re-checks fields defensively; do it well, and the rest of the application operates on structures it can trust. Python gives you two tools with overlapping jobs and very different philosophies: dataclasses, which generate boilerplate-free classes with no opinions about correctness, and Pydantic, which coerces and validates on construction and refuses to build an invalid object at all.

This lesson explains where each belongs, how to express real validation rules, and how to keep the boundary strict while the interior stays simple.


Two philosophies in one language

A dataclass is an ergonomic way to declare a record: give it fields and types, and you receive __init__, __repr__, __eq__, and hashing behaviour without writing any of it. Validation remains your problem — which is a feature when the record is internal and already trusted, and a liability at a network boundary. Pydantic flips the contract: you declare the shape and the rules, and construction either yields a valid instance or raises with a structured error that names every offending field.

python
from dataclasses import dataclass, field, asdict
from typing import List

@dataclass
class Address:
    street: str
    city: str
    postcode: str

@dataclass
class Customer:
    name: str
    email: str
    addresses: List[Address] = field(default_factory=list)
    tags: List[str] = field(default_factory=list)

c = Customer("Ada", "[email protected]", [Address("1 Main St", "London", "N1 1AA")])
print(asdict(c)["addresses"][0]["city"])   # London — easy serialisation
print(c == Customer("Ada", "[email protected]", [Address("1 Main St", "London", "N1 1AA")]))

Note the default_factory usage. Mutable defaults such as tags: List[str] = [] are shared across every instance — a bug that produces baffling cross-object leakage — and the factory form is the correct idiom every time a default is a list, dict, or set.

Immutability, ordering, and the small powers of dataclasses

Once the record is declared, the remaining decisions are about mutability and structure. frozen=True makes instances hashable and safe to share across threads; order=True gives you comparison operators for free; slots=True (Python 3.10+) cuts per-instance memory by removing the instance dictionary, which matters when you are holding hundreds of thousands of rows.

DeclarationEffectUse when
@dataclassMutable, normal dictRecords that get updated in place
@dataclass(frozen=True)Immutable, hashableValues used as dict keys or in sets
@dataclass(order=True)__lt__ and friends generatedRecords sorted by their fields
@dataclass(slots=True)No per-instance __dict__Very large collections
@dataclass(kw_only=True)All fields keyword-onlyMany optional fields, readability
field(default_factory=...)Per-instance mutable defaultLists, dicts, sets
python
from dataclasses import dataclass, replace

@dataclass(frozen=True, slots=True)
class Money:
    amount: int          # minor units: pence, cents
    currency: str

    def __post_init__(self):
        if self.currency not in {"GBP", "USD", "EUR"}:
            raise ValueError(f"unsupported currency: {self.currency}")

price = Money(1250, "GBP")
discounted = replace(price, amount=999)     # returns a new instance
print(price, discounted, hash(price) is not None)

__post_init__ is where dataclass-level invariants belong — it runs at the end of generated __init__, so the object is checked before any caller can hold it. replace is the idiomatic way to derive a new value from a frozen record, and it preserves the type, so subclassed records do not silently degrade.

Pydantic: the boundary that refuses invalid data

At a trust boundary, silent tolerance is the enemy. Pydantic models declare types, coerce obvious representations ("5" to 5, string dates to datetime), and raise a single ValidationError listing every problem it found — which is exactly what you want to send back to a client in one round trip instead of failing one field at a time.

python
from pydantic import BaseModel, Field, ValidationError
from typing import Optional
from datetime import date

class Signup(BaseModel):
    email: str = Field(pattern=r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
    password: str = Field(min_length=12, max_length=128)
    birthday: Optional[date] = None
    referrer: Optional[str] = None

    model_config = {"str_strip_whitespace": True}

try:
    user = Signup(email="  [email protected] ", password="correct horse battery", birthday="1815-12-10")
    print(user.model_dump())            # plain dict for storage
    print(user.model_dump_json())       # JSON string for transport
except ValidationError as exc:
    print(exc.errors())                 # every field problem at once

Three details make this production-ready. Coercion of the birthday string happens because the field declares date, so callers may send either form. Whitespace stripping is a configuration flag rather than a per-field validator you must remember. And model_dump() / model_dump_json() give you canonical serialisation without hand-written asdict plumbing.

Rules, nested models, and composition

Real schemas need more than type checks: cross-field constraints, nested structures, and lists whose items must each be valid. Pydantic expresses all three by composition, which keeps each model small enough to read in one screen.

python
from pydantic import BaseModel, model_validator, field_validator
from typing import List

class LineItem(BaseModel):
    sku: str
    quantity: int = Field(gt=0)
    unit_price: float = Field(gt=0)

class Order(BaseModel):
    customer_id: str
    items: List[LineItem] = Field(min_length=1)
    ship_to: Address

    @field_validator("customer_id")
    @classmethod
    def customer_id_format(cls, v: str) -> str:
        if not v.startswith("cus_"):
            raise ValueError("customer ids must start with cus_")
        return v

    @model_validator(mode="after")
    def total_must_be_positive(self):
        if sum(i.quantity * i.unit_price for i in self.items) <= 0:
            raise ValueError("order total must be positive")
        return self

order = Order(
    customer_id="cus_42",
    items=[{"sku": "A", "quantity": 2, "unit_price": 5.0}],
    ship_to={"street": "1 Main St", "city": "London", "postcode": "N1 1AA"},
)
print(order.model_dump()["items"][0]["sku"])    # A

Field validators normalise one field; model validators see the whole object and are the right place for invariants that span fields. Note that nested dicts are coerced automatically into LineItem and Address instances, so a parsed JSON body and a constructed Python object take the same code path.

Choosing between them

RequirementChooseWhy
Internal record, no external inputdataclassZero dependencies, minimal surface
Hashable value used as a keyfrozen dataclassCheap hashing, no validation needed
JSON or form data from a clientPydanticCoercion plus structured errors
Config loaded from YAML or envPydanticType coercion and defaults in one place
Performance-critical inner loopdataclass(slots=True)No dict, no validation overhead
Public API schema and docsPydanticJSON schema generation for free
Library code that must not force a dependencydataclassStandard library only

A pattern that gets the best of both is to validate at the boundary with Pydantic and convert immediately into frozen dataclasses for the interior. The application core then depends on nothing but the standard library, the boundary rejects garbage once, and the deep code never re-validates.

The conversion layer is usually one small function per model — Signup.to_domain() — and it is the right place to apply defaults that are policy rather than syntax: a plan name that falls back to "free", a locale that falls back to the application default. Keeping those decisions out of the model declaration means the schema stays a faithful picture of the wire format while the domain objects stay a faithful picture of the business rules, and neither has to pretend to be the other.

Modelling mistakes that surface in production

The classic failure is modelling money as a float — binary floating point cannot represent tenths exactly, and the rounding drift accumulates across a ledger. Store minor units as integers or use Decimal. The second is using optional fields where "absent" and "empty" mean different things; choose None versus "" deliberately and document which one the rest of the system expects. The third is putting validation only in the API layer while background jobs construct the same objects directly — if a job can build it, it must pass the same rules, so move invariants into the model rather than the handler.

Finally, version your schemas. A model is a contract with every producer of its data, and renaming a field without an alias breaks callers you will not hear from until they fail in ways that look like their bug rather than yours.

Common Mistakes

Mutable default values on dataclass fields

Fix: Use field(default_factory=list) so each instance gets its own collection

Validating only in the HTTP handler while jobs construct objects directly

Fix: Put the rules in the model so every construction path is checked

Representing money with floats

Fix: Store integer minor units or use Decimal, and round only at the presentation layer

Swallowing ValidationError and returning a generic 500

Fix: Return the structured errors so the caller learns which fields failed

Deep-copying models at every layer for safety

Fix: Make boundary models immutable and convert once into interior dataclasses

Best Practices

  • Validate once at the trust boundary and keep the interior typed and simple
  • Use frozen, slotted dataclasses for values shared across threads or held in bulk
  • Prefer model validators for cross-field invariants rather than handler-side checks
  • Generate JSON schemas from Pydantic models so client code can be generated too
  • Document absent versus empty semantics for every optional string field

Key Takeaways

  • dataclasses remove boilerplate; Pydantic adds a correctness guarantee at construction
  • frozen plus slots gives hashable, memory-lean records for hot paths
  • Field validators normalise one field; model validators enforce cross-field rules
  • Nested models coerce automatically, so dict input and object input take one path
  • Money, optionality, and schema versioning are the three production traps to design against
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement