Lesson 19 of 52Objects
Dataclasses
Replace boilerplate classes with @dataclass, choose the right options, and know when NamedTuple or Pydantic fits better.
A huge share of the classes you will write are just containers for data: a User, an Order, a Point, a config. Writing __init__, __repr__ and __eq__ by hand for each one is boring and easy to get wrong. The dataclasses module, in the standard library since Python 3.7, writes them for you from a few type-annotated lines. You will see dataclasses all over modern codebases, and FastAPI's Pydantic models follow the same idea.
Before and after
Here is a class written the long way, next to the dataclass version that generates the same methods.
class Book:
def __init__(self, title: str, author: str, pages: int = 0):
self.title = title
self.author = author
self.pages = pages
def __repr__(self):
return f"Book(title={self.title!r}, author={self.author!r}, pages={self.pages!r})"
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title, self.author, self.pages) == (other.title, other.author, other.pages)from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int = 0The class-level annotations (title: str) declare the fields. @dataclass reads them, in order, and generates __init__, __repr__ and __eq__.
Press Run (⌘ Enter) to see what happens.The type annotations are not enforced. Book(1, 2, "three") runs fine. They document intent and power editors and type checkers, which you will meet in the type hints lesson.
@dataclass generate for you?Defaults and field(default_factory=...)
Fields with defaults must come after fields without, just like function parameters. And you cannot write a mutable default like tags: list[str] = []. Remember the shared-list trap from the classes lesson: that one list would be shared by every instance. Dataclasses refuse it with a ValueError at class definition time.
The fix is field(default_factory=list): a function called once per instance to build a fresh default.
Press Run (⌘ Enter) to see what happens.field() takes other options too, such as repr=False to hide a field (good for passwords) and compare=False to leave it out of ==.
What does this print?
from dataclasses import dataclass, field
@dataclass
class Team:
name: str
members: list = field(default_factory=list)
x = Team("x")
y = Team("y")
x.members.append("Leo")
print(len(y.members))Keyword-only fields: kw_only=True and KW_ONLY
The "defaults must come last" rule bites hardest with inheritance. A subclass's fields are added after the parent's, so if the parent has any default, every field in the child needs one too. In a real codebase this shows up the first time someone subclasses a base event or base model:
Press Run (⌘ Enter) to see what happens.@dataclass(kw_only=True) (Python 3.10+) makes every field declared in that class keyword-only. Keyword-only parameters are moved to the end of __init__, so the ordering rule no longer applies to them. Note that it does not change the parent's fields: name and priority are still positional on Alert.
The _: KW_ONLY marker does the same for every field after it, like the bare * in a function signature from Arguments, *args and **kwargs. The name _ is a convention; the type KW_ONLY is what matters. You can also set it per field with field(kw_only=True).
Keyword-only fields are worth using even without inheritance. Job("backup", 3, 5.0) makes the reader count; Job("backup", retries=3, timeout=5.0) does not, and you can add or reorder options later without breaking callers. A sensible team default for records with more than two or three fields is kw_only=True.
field() options in depth
field() is how you configure one field. The options you will use at work:
Press Run (⌘ Enter) to see what happens.repr=Falsekeeps a field out of the printed form. This matters more than it looks: dataclass reprs end up in logs, exception messages and error trackers, and a leaked API key in a log is a real incident. Hide secrets, tokens and large blobs.compare=Falseleaves a field out of==, ordering and the generated hash. Use it for counters, caches and timestamps that should not make two otherwise equal values different.init=Falseremoves the field from__init__. It must then get a value fromdefault,default_factoryor__post_init__.metadatais a read-only mapping that dataclasses ignore completely. It exists for your tools: a config loader that readsmetadata["env"], a serializer that reads a column name.dataclasses.fields()returns every field with its options, which is how such tools discover them.hash=overrides whether the field is part of__hash__. You rarely need it;compare=Falseusually expresses the intent better.
repr=False only changes the repr. The value is still on the object, in vars() and in asdict(), so anything that dumps the whole object still exposes it. For real secret handling, Pydantic's SecretStr or a small wrapper class with its own repr is safer.
frozen, order and slots
The @dataclass(...) decorator takes switches that change what is generated.
Plain @dataclass gives you these three. Instances are mutable and unhashable.
Press Run (⌘ Enter) to see what happens.Frozen dataclasses are a great default for value objects: things defined entirely by their data, like a money amount, a coordinate or a version. They are safe to share, safe to use as keys, and cannot change behind your back.
Point(x, y) dataclass as a dictionary key. What is the simplest correct option?Validation with __post_init__
The generated __init__ just assigns fields. If you need to validate or derive values, define __post_init__. It runs right after the fields are set.
Press Run (⌘ Enter) to see what happens.InitVar: constructor inputs that are not fields
Sometimes the caller should pass something that you only need during construction. A database config is a good example: callers pass a connection string, but the rest of the code wants host, port and database. Annotating a field as InitVar[...] makes it an __init__ parameter that is handed to __post_init__ and then thrown away. It is never stored on the instance.
Press Run (⌘ Enter) to see what happens.Notice what did not happen: the password inside the DSN is not stored on the object and does not appear in the repr. Combined with init=False fields, InitVar is the standard way to compute fields from inputs.
If a derived value should always track other fields, do not store it at all. A @property (or functools.cached_property on a frozen or rarely changing object) computes it on access, so it can never go stale when a field changes. Store a computed field only when computing it is expensive or when it must be part of == and the repr.
Changing frozen values: replace
A frozen dataclass cannot be changed, so how do you apply a discount to a Money? You make a new one with some fields swapped. dataclasses.replace does exactly that, and Python 3.13 added the general copy.replace, which works on dataclasses, named tuples, datetime objects and any class that defines __replace__.
Press Run (⌘ Enter) to see what happens.replace builds the new object by calling __init__, so __post_init__ runs again and your validation still protects you. Two consequences to know. Fields with init=False cannot be passed to replace (it raises), and they are recomputed or reset to their defaults on the copy. And replace is shallow: a list field in the copy is the same list object as in the original, so freezing the dataclass does not freeze the lists inside it. Use tuples or frozenset for collections in value objects.
This "copy with changes" style is how immutable state is updated in many codebases, from config overrides in tests (replace(DEFAULTS, debug=True)) to reducers in event-driven code.
What does this print?
from dataclasses import dataclass, replace @dataclass(frozen=True) class Point: x: int y: int = 0 a = Point(1) b = replace(a, y=5) print(a, b, a == Point(1))
asdict deep-copies, and that costs time
To turn a dataclass into JSON you usually go through dataclasses.asdict. It is convenient, and it recurses into nested dataclasses, lists, tuples and dicts. It also deep-copies every value on the way, which you can see and measure:
Press Run (⌘ Enter) to see what happens.The copying makes the result safe to modify, but in a hot path (serializing thousands of objects per request) it can show up in a profiler. Your options, from simplest:
- Do nothing until a profile shows
asdictmatters. For most APIs it does not. - Shallow conversion with
{f.name: getattr(obj, f.name) for f in fields(obj)}when you know the values are already JSON-friendly and you will not mutate the result. - A purpose-built serializer such as
msgspec,cattrsor Pydantic's dataclass support, which are much faster and also handle dates, enums and validation. Check each project's docs for current dataclass support.
astuple has the same deep-copy behaviour. And asdict does not convert datetime, Decimal or enum values into JSON types; json.dumps will still need a default= for those.
NamedTuple: a tuple with names
typing.NamedTuple is the other lightweight option. It creates a real tuple subclass: immutable, hashable, unpackable and indexable, with named fields on top.
Press Run (⌘ Enter) to see what happens.Pick a NamedTuple for small, immutable records that are naturally tuples (rows from a CSV, coordinates, function results). Pick a dataclass for everything else: it can be mutable, has more options and does not pretend to be a sequence.
When to reach for Pydantic
Dataclasses trust their input. That is fine for data your own code creates. For data from the outside world (JSON from an HTTP request, environment variables, a config file) you want validation and conversion: "42" should become 42, a missing email should be a clear error. That is what Pydantic does, and it is the backbone of FastAPI. You will use it heavily in the Python Backend course.
from pydantic import BaseModel
class SignUp(BaseModel):
email: str
age: int
SignUp(email="ada@example.com", age="36") # age is converted to 36
SignUp(email="ada@example.com", age="old") # ValidationErrorChoosing a record type
Five tools cover almost every "bag of named fields" in Python. They differ in what exists at run time, which is what decides speed, memory and safety.
| Tool | At run time it is | Mutable | Validates input | Relative cost | Reach for it when |
|---|---|---|---|---|---|
@dataclass | a normal class with generated methods | yes (or frozen=True) | no | like a hand-written class; slots=True saves memory | internal domain objects and value objects |
NamedTuple | a tuple subclass | no | no | cheapest object; small and fast to create | small immutable records that unpack like tuples |
TypedDict | a plain dict (types are checker-only) | yes | no | dict cost, no class instance at all | JSON-shaped data, **kwargs, gradual typing of dict code |
attrs (@define) | a normal class, slotted by default | yes (or @frozen) | opt-in validators and converters | close to dataclasses | you want validators and converters without a framework |
Pydantic BaseModel | a class that parses and validates on every creation | yes (or frozen config) | yes, with type coercion | noticeably slower to create, because validation runs every time | data crossing a trust boundary: HTTP, config, queues |
The rule most teams settle on: validate at the edges, trust in the middle. Parse untrusted input once with Pydantic at the boundary, then pass plain dataclasses (or the validated model) through the core of the system, where repeated validation would only cost time. TypedDict is the right choice when the data really is a dict that you get from and give to other code, and you only want the checker to know its keys. attrs is the library dataclasses were modelled on; it is still worth knowing because many established codebases use it.
Pick the tool for each job.
Line items and a cart
Model a shopping cart with two dataclasses.
LineItem is a frozen dataclass with fields name: str, price_cents: int and qty: int = 1. In __post_init__, raise ValueError if price_cents is negative or qty is less than 1.
Cart is a dataclass with owner: str and items: list[LineItem] that defaults to an empty list per cart. It has:
add(item)to append a line item,total()returning the sum ofprice_cents * qtyover all items.
c = Cart("Ada")
c.add(LineItem("pen", 150, 2))
c.add(LineItem("pad", 400))
c.total() # 700
LineItem("x", 1) == LineItem("x", 1) # True
LineItem("x", -5) # ValueError- @dataclass
- Generates
__init__,__repr__and__eq__from annotated class fields. - default_factory
field(default_factory=list)builds a fresh default for each instance.- frozen=True
- Makes a dataclass immutable and hashable, ideal for value objects.
- __post_init__
- A hook run after the generated
__init__, used to validate or compute fields. - NamedTuple
- An immutable tuple subclass with named fields, created with
typing.NamedTuple. - kw_only
@dataclass(kw_only=True)or_: KW_ONLYmakes fields keyword-only, which also lifts the defaults-last rule.- InitVar
- A constructor-only parameter passed to
__post_init__and never stored on the instance. - replace
dataclasses.replaceorcopy.replace(3.13) builds a new object with some fields changed; shallow.- asdict
- Recursively converts a dataclass to a dict, deep-copying every value on the way.