Skip to content

Lesson 1 of 9 · 20m

Dataclasses That Earn Their Keep

Dataclasses are not structs with extra syntax — used well, they are the cheapest correct way to model data with defaults, ordering, immutability, and validation.

Most Python classes fail before lunch because they confuse record-shaped data with service-shaped behavior. When I review a junior's first OO design, the class usually has twenty mutable attributes, a constructor copied from a Java tutorial, and no answer to the question 'what two values of this object mean equal?' Dataclasses solve the record half of that problem with almost no ceremony.

Start with the record, not the ritual

from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Money:
    cents: int
    currency: str

Those two arguments matter. frozen=True makes accidental mutation loud instead of corrupting totals in three places. slots=True removes the per-instance dict, saves memory when you instantiate thousands of rows, and makes typos fail immediately.

Defaults are a trap door

@dataclass
class Job:
    name: str
    retries: int = 3
    tags: list[str] = field(default_factory=list)

Never write tags: list[str] = []. Mutable defaults are shared across every instance, which means one job's tag appears in every job. field(default_factory=list) creates a fresh list per object. The same rule applies to dicts, sets, and objects you construct during initialization.

Validate in __post_init__

@dataclass(frozen=True)
class Percentage:
    value: int

    def __post_init__(self) -> None:
        if not 0 <= self.value <= 100:
            raise ValueError("percentage must be 0..100")

Dataclasses generate construction, equality, and representation; they do not enforce meaning. If a value is invalid, reject it at the boundary. A Percentage(140) should never exist long enough to reach your database.

Ordering and equality are semantic decisions

order=True generates comparison methods from fields in declaration order. That is convenient until someone reorders fields and changes the sort order of invoices across a deployment. If ordering matters to the business, implement __lt__ explicitly or sort with a key function. Likewise, eq=False plus unsafe_hash tricks are not free — identity and equality are domain questions.

Field notes

  • dataclasses.replace(obj, cents=new_cents) is the idiomatic way to update a frozen value object.
  • kw_only=True in Python 3.10+ is cheap insurance against argument-order mistakes in long constructors.
  • Dataclasses are not pydantic. They validate what you write, not untrusted JSON at process boundaries.
  • If the class owns sockets, sessions, transactions, or retries, it is a service — not a dataclass.

Was this lesson helpful?

Sign in to rate