Sub topic 13
Choosing between dataclasses, NamedTuple and other tools
This chapter assumes you can write a basic @dataclass, you know what frozen=True and slots=True do, and you understand the difference between mutable and immutable objects. The goal is to decide which tool fits a given piece of data. Dataclasses are often the right choice, but not always.
The options at a glance
Python has several ways to describe "a bundle of named values". They differ in what the object is at runtime, what is checked, and what behavior you get for free.
| Tool | Runtime type | Mutable | Validates types at runtime | Part of stdlib |
|---|---|---|---|---|
| Plain class | Your class | Yes | Only if you write it | Yes |
| `@dataclass` | Your class | Yes, unless `frozen=True` | No | Yes |
| `NamedTuple` | A `tuple` subclass | No | No | Yes |
| `TypedDict` | A plain `dict` | Yes | No | Yes |
| `attrs` | Your class | Yes, unless frozen | Optional validators | No |
| `pydantic` | A `BaseModel` subclass | Yes, unless frozen | Yes, with conversion | No |
Annotations in the first four rows are only hints. Python does not enforce them. Only the libraries that add validation will reject or convert a wrong value.
Dataclass versus NamedTuple
These two are the closest competitors. Both generate __init__, __repr__ and __eq__, and both declare fields with annotations. The difference is that a NamedTuple instance is a tuple.
from dataclasses import dataclass
from typing import NamedTuple
class PointNT(NamedTuple):
x: int
y: int
@dataclass(frozen=True)
class PointDC:
x: int
y: int
nt = PointNT(1, 2)
dc = PointDC(1, 2)
x, y = nt # unpacking works because a tuple is iterable
print(x, y) # 1 2
print(nt[0], len(nt)) # 1 2
print(nt == (1, 2)) # True
print(dc == (1, 2)) # False
try:
x, y = dc
except TypeError as exc:
print(exc) # cannot unpack non-iterable PointDC object
print(nt._replace(x=5)) # PointNT(x=5, y=2)
print(nt._asdict()) # {'x': 1, 'y': 2}Every tuple behavior comes with the NamedTuple, whether you want it or not: indexing, slicing, iteration, unpacking and comparison with any other tuple. That is useful when the value must pass through code that expects a tuple, for example a function that returns (row, column) and is already used with unpacking. It becomes a hazard when it lets unrelated values compare as equal.
from dataclasses import dataclass
from typing import NamedTuple
class MetersNT(NamedTuple):
value: float
class FeetNT(NamedTuple):
value: float
@dataclass
class MetersDC:
value: float
@dataclass
class FeetDC:
value: float
print(MetersNT(1.0) == FeetNT(1.0)) # True (both are just (1.0,))
print(MetersDC(1.0) == FeetDC(1.0)) # False (the generated __eq__ checks the class)The generated __eq__ of a dataclass returns NotImplemented for an instance of a different class, so Python falls back to identity and the result is False. If you model distinct concepts, this strictness catches mistakes.
What dataclasses can do that NamedTuple cannot
- Mutability. A
NamedTupleis always immutable. A dataclass is mutable by default and can be frozen when you ask for it. - Mutable defaults through
default_factory. Tuples are fixed-size values, so a per-instance list is an awkward fit. __post_init__,InitVarandfield(init=False). These hooks let you validate input and compute derived fields. ANamedTuplehas no equivalent. You would override__new__, which is clumsy.- Per-field control. Options such as
compare=Falseandrepr=Falseare not available on aNamedTuple. - Ordinary inheritance. A
NamedTupleclass cannot be extended with new fields, and the class syntax does not support multiple inheritance. Dataclasses inherit fields as covered in the inheritance chapter. - Opt-in ordering.
order=Truecompares only instances of the same class. ANamedTuplecompares like any tuple, field by field, even with an unrelated tuple.
What NamedTuple does better
- It is a tuple. It works anywhere a tuple is accepted, and it unpacks naturally.
- It is immutable and hashable by default. You do not need to remember
frozen=True. Two fields holding hashable values give a hashable object. - It is compact. A tuple instance has no per-instance
__dict__. Aslots=Truedataclass gets a similar saving, but a plain dataclass does not. - It is simple. There are no generated-method options to learn.
The usual rule is this. Choose NamedTuple for small, immutable records that act as tuples, such as return values or coordinates. Choose a dataclass when the object has its own identity and behavior, or when it needs any of the hooks above.
Dataclass versus a plain class
A dataclass is still a regular class. You can add methods, properties and class variables to it. The decorator only saves you from writing the repetitive parts. A hand-written class is the better choice in these cases:
- Constructor arguments do not map one-to-one to stored attributes. For example,
__init__opens a file, parses a string, or connects to a service. - The object guards invariants across several attributes and exposes them through properties, so the stored state is private.
- Equality should not be "all fields equal". An entity compared only by its database ID is an example. You can often express this with
field(compare=False), but if you end up overriding__eq__,__hash__and__init__by hand, the decorator is no longer helping.
A good test is to look at your dataclass and count how many generated methods you replaced. If you replaced most of them, write a plain class.
Dataclass versus TypedDict
A TypedDict describes the shape of a dictionary for the type checker. At runtime it is a plain dict.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: int
movie: Movie = {"title": "Alien", "year": 1979}
print(type(movie)) # <class 'dict'>
print(movie["title"]) # Alien
bad: Movie = {"title": 1} # a type checker flags this; Python does not
print(bad) # {'title': 1}Use it when the data already is a dictionary, typically parsed JSON or keyword arguments, and you want type-checker help without converting anything. Use a dataclass when you want attribute access, methods and defaults. Converting a dict to a dataclass with Movie(**data) also fails on unknown or missing keys, which gives you a basic structural check at the boundary.
Third-party tools: attrs and pydantic
The standard library does not validate types or convert values. Two popular packages cover that.
attrs is the library that inspired dataclasses. It offers a superset of the features: validators, converters, and slots=True as the default in its modern define API.
import attrs
@attrs.define
class Point:
x: int
y: int = attrs.field(default=0, validator=attrs.validators.instance_of(int))
print(Point(1)) # Point(x=1, y=0)
try:
Point(1, "2")
except TypeError as exc:
print("rejected:", type(exc).__name__)pydantic is built around parsing and validating untrusted input. A BaseModel reads annotations and converts or rejects values at construction time.
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
user = User(name="Ana", age="31") # the string "31" is converted
print(user.age, type(user.age)) # 31 <class 'int'>Both examples need pip install attrs pydantic. Neither is in the standard library, so a project that must stay dependency-free cannot use them.
Which one should you pick?
The flowchart condenses the questions to ask, in order.
Some practical tie-breakers:
- Dependencies. A library or small script often benefits from staying within the standard library, which favors dataclasses and
NamedTuple. - Python version.
slots=Trueandkw_only=Trueneed Python 3.10 or newer. On older versions,attrsgives you both. - Serialization.
asdicthandles nested dataclasses, lists and dicts. For richer conversion to and from JSON, with type coercion, pydantic is much more capable. - Performance. Construction of a dataclass is a normal Python
__init__call. Validation libraries do extra work per instance. Measure with your real data before you let speed decide the choice. - Migration. Moving between dataclass, attrs and pydantic is usually cheap because all three use annotated fields. Moving to or from
NamedTuplechanges behavior (unpacking, equality), so check call sites.
Common mistakes
- Using a
NamedTuplefor objects that should not be unpacked or compared to tuples. Two unrelated types become equal, as theMetersNTandFeetNTexample showed. - Expecting dataclasses to validate. Add
__post_init__checks or a validating library. - Reaching for pydantic for purely internal data. If your own code constructs the object with correct values, validation is overhead you do not need.
- Fighting the decorator. If you override most generated methods, switch to a plain class.
- Forgetting that a mutable dataclass with
eq=Trueis unhashable. If you need dict keys or set members, addfrozen=True, or use aNamedTuple.
Exercise
You write a function that returns a minimum and a maximum, and callers already write lo, hi = bounds(data). A teammate proposes a dataclass Bounds(lo, hi) and says it is a drop-in replacement. What breaks, and which stdlib alternative keeps the old call sites working?
Show answer
A dataclass instance is not iterable, so lo, hi = bounds(data) raises TypeError: cannot unpack non-iterable Bounds object. A NamedTuple named Bounds with fields lo and hi keeps unpacking, indexing and comparison with plain tuples working, and it still gives you named attribute access.
Exercise
A web service receives JSON such as {"name": "Ana", "age": "31"} from clients and must reject bad data and convert "31" to the integer 31. Which tool from this chapter fits best, and why is a plain @dataclass with age: int not enough?
Show answer
pydantic fits best, because a BaseModel validates and converts values when it is constructed. A dataclass annotation is only a hint. Person(name="Ana", age="31") would store the string "31" without error, so you would have to write the checks and conversions yourself in __post_init__.
Exercise
Two classes A and B are both dataclasses with a single field value: int. Two other classes C and D are both NamedTuple types with the same single field. What do A(1) == B(1) and C(1) == D(1) evaluate to, and why?
Show answer
A(1) == B(1) is False, because the generated __eq__ of a dataclass only compares instances of the same class. C(1) == D(1) is True, because both are tuples equal to (1,), and tuple equality ignores the subclass.