Skip to content

Lesson 19 of 52Objects

Dataclasses

Replace boilerplate classes with @dataclass, choose the right options, and know when NamedTuple or Pydantic fits better.

20 min read0/6 questions

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)

The class-level annotations (title: str) declare the fields. @dataclass reads them, in order, and generates __init__, __repr__ and __eq__.

Python
from dataclasses import dataclass @dataclassclass Book: title: str author: str pages: int = 0 b = Book("Night Train", "Priya", 412)print(b)print(b == Book("Night Train", "Priya", 412))print(Book("Notes", "Ada"))b.pages += 1print(b.pages)
Output
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.

Quick check
Which methods does a plain @dataclass generate for you?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from dataclasses import dataclass, field @dataclassclass Cart: owner: str items: list[str] = field(default_factory=list) discount: float = 0.0 a = Cart("Ada")b = Cart("Sam")a.items.append("book")print(a)print(b) # b has its own empty list try: @dataclass class Broken: tags: list = []except ValueError as e: print("ValueError:", e)
Output
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 ==.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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:

Python
from dataclasses import dataclass, KW_ONLY @dataclassclass Event: name: str priority: int = 0 try: @dataclass class Alert(Event): channel: str # no default, after a defaultexcept TypeError as err: print("TypeError:", err) @dataclass(kw_only=True)class Alert(Event): channel: str print(Alert("disk full", channel="#ops")) @dataclassclass Job: name: str _: KW_ONLY retries: int = 3 timeout: float = 30.0 print(Job("backup", timeout=5.0))try: Job("backup", 5)except TypeError as err: print("TypeError:", err)
Output
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:

Python
from dataclasses import dataclass, field, fields @dataclassclass ApiClient: base_url: str api_key: str = field(repr=False) timeout: float = field(default=10.0, metadata={"env": "API_TIMEOUT"}) request_count: int = field(default=0, init=False, compare=False) a = ApiClient("https://api.example.com", "sk-secret-123")b = ApiClient("https://api.example.com", "sk-secret-123")a.request_count = 7print(a)print(a == b)for f in fields(ApiClient): print(f.name, f.init, f.repr, f.compare, dict(f.metadata))
Output
Press Run (⌘ Enter) to see what happens.
  • repr=False keeps 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=False leaves 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=False removes the field from __init__. It must then get a value from default, default_factory or __post_init__.
  • metadata is a read-only mapping that dataclasses ignore completely. It exists for your tools: a config loader that reads metadata["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=False usually 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.

What @dataclass builds, by option
  1. __init__, __repr__, __eq__always (the defaults)
  2. __lt__, __le__, __gt__, __ge__order=True: compares fields as a tuple, in order
  3. __setattr__ raises, __hash__ addedfrozen=True: immutable and hashable
  4. __slots__slots=True: no per-instance __dict__, less memory, faster access
  5. __post_init__ hookyour method, called at the end of __init__

Plain @dataclass gives you these three. Instances are mutable and unhashable.

1/5
Python
from dataclasses import dataclass, FrozenInstanceError @dataclass(frozen=True, order=True)class Version: major: int minor: int patch: int = 0 vs = [Version(1, 10), Version(1, 2, 5), Version(0, 9)]print(sorted(vs))print(max(vs))print({Version(1, 0): "first stable"}) # frozen makes it hashable v = Version(2, 0)try: v.major = 3except FrozenInstanceError: print("frozen: cannot change major")
Output
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.

Quick check
You want to use a Point(x, y) dataclass as a dictionary key. What is the simplest correct option?
Need a nudge? A hint rules out a wrong answer.

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.

Python
from dataclasses import dataclass, field @dataclassclass Product: name: str price_cents: int slug: str = field(init=False) # not a constructor argument def __post_init__(self): if self.price_cents < 0: raise ValueError("price cannot be negative") self.slug = self.name.lower().replace(" ", "-") print(Product("Desk Lamp", 2999))try: Product("Bad", -1)except ValueError as e: print("rejected:", e)
Output
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.

Python
from dataclasses import dataclass, field, fields, InitVarfrom urllib.parse import urlsplit @dataclassclass DbConfig: dsn: InitVar[str] pool_size: int = 5 host: str = field(init=False) port: int = field(init=False) database: str = field(init=False) def __post_init__(self, dsn: str) -> None: parts = urlsplit(dsn) self.host = parts.hostname or "localhost" self.port = parts.port or 5432 self.database = parts.path.lstrip("/") cfg = DbConfig("postgresql://app:secret@db.internal:6543/shop", pool_size=10)print(cfg)print([f.name for f in fields(cfg)])print(hasattr(cfg, "dsn"))
Output
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__.

Python
import copyfrom dataclasses import dataclass, replace @dataclass(frozen=True)class Money: amount_cents: int currency: str = "GBP" def __post_init__(self): if self.amount_cents < 0: raise ValueError("negative money") price = Money(1999)sale = replace(price, amount_cents=1499)print(price, sale)print(copy.replace(price, currency="EUR")) # 3.13+, same idea, any type with __replace__ try: replace(price, amount_cents=-1)except ValueError as err: print("ValueError:", err)
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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:

Python
import timeitfrom dataclasses import dataclass, asdict, field @dataclassclass Line: sku: str qty: int @dataclassclass Order: id: int lines: list[Line] = field(default_factory=list) order = Order(1, [Line("A1", 2), Line("B7", 1)])d = asdict(order)print(d)print(d["lines"] is order.lines) # a new list, deep-copiedd["lines"][0]["qty"] = 99print(order.lines[0].qty) # original untouched big = Order(2, [Line(f"S{i}", i) for i in range(200)])deep = timeit.timeit(lambda: asdict(big), number=100)flat = timeit.timeit(lambda: {"id": big.id, "lines": big.lines}, number=100)print(f"asdict: {deep / 100 * 1e6:.0f} us per call, shallow dict: {flat / 100 * 1e6:.2f} us per call")
Output
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 asdict matters. 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, cattrs or 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.

Python
from typing import NamedTuple class Point(NamedTuple): x: float y: float = 0.0 p = Point(3, 4)x, y = p # unpacks like a tupleprint(p, p.x, p[1], x + y)print(p._replace(y=10)) # "change" by making a new one
Output
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")  # ValidationError

Choosing 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.

ToolAt run time it isMutableValidates inputRelative costReach for it when
@dataclassa normal class with generated methodsyes (or frozen=True)nolike a hand-written class; slots=True saves memoryinternal domain objects and value objects
NamedTuplea tuple subclassnonocheapest object; small and fast to createsmall immutable records that unpack like tuples
TypedDicta plain dict (types are checker-only)yesnodict cost, no class instance at allJSON-shaped data, **kwargs, gradual typing of dict code
attrs (@define)a normal class, slotted by defaultyes (or @frozen)opt-in validators and convertersclose to dataclassesyou want validators and converters without a framework
Pydantic BaseModela class that parses and validates on every creationyes (or frozen config)yes, with type coercionnoticeably slower to create, because validation runs every timedata 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.

Quick check
A service receives order JSON from a partner API, then passes each order through ten internal pricing functions. What is the best split?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/4 matched

Pick the tool for each job.

Choose an item, then its match on the other side.
ChallengeMedium

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 of price_cents * qty over 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
Python
from dataclasses import dataclass, field class LineItem: # Make this a frozen dataclass with validation in __post_init__. pass class Cart: # Make this a dataclass whose items default to a new empty list. pass
Key terms
@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_ONLY makes 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.replace or copy.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.