Sub topic 13
Choosing between dataclasses, NamedTuple and other tools
This chapter assumes you know how to define a dataclass, use field(), and read type annotations. It also assumes you know the difference between mutable and immutable objects. Here you will compare dataclasses with the main alternatives and pick one for a given job.
What you are choosing between
Python has several ways to hold a few named values. Each makes different trade-offs about mutability, memory, validation and dependencies.
| Tool | Mutable | Generated methods | Behaves like a tuple | Extra dependency |
|---|---|---|---|---|
| Plain class | Yes | None, you write them | No | No |
| `@dataclass` | Yes, unless `frozen=True` | `__init__`, `__repr__`, `__eq__`, optional ordering and hash | No | No |
| `NamedTuple` | No | `__init__`, `__repr__`, `__eq__`, ordering | Yes | No |
| `dict` | Yes | None | No | No |
| `attrs` or `pydantic` | Configurable | Many, plus validators | No | Yes |
Dataclass versus NamedTuple
A NamedTuple is a tuple whose positions have names. A dataclass is an ordinary class with generated methods. The same data looks like this in each form:
from dataclasses import dataclass
from typing import NamedTuple
class PointNT(NamedTuple):
x: float
y: float = 0.0
@dataclass
class PointDC:
x: float
y: float = 0.0
nt = PointNT(1.0, 2.0)
dc = PointDC(1.0, 2.0)
x, y = nt # tuples unpack
print(nt[0], nt == (1.0, 2.0)) # 1.0 True
print(dc == (1.0, 2.0)) # False
dc.x = 9.0 # dataclasses are mutable by default
try:
nt.x = 9.0
except AttributeError:
print("NamedTuple fields are read-only")Because a NamedTuple is a tuple, it unpacks, indexes, and compares equal to a plain tuple with the same values. That is useful when you return several values from a function and want callers to keep using tuple unpacking. It can also surprise you. A PointNT(1, 2) equals any other (1, 2) tuple, including one from an unrelated NamedTuple type.
A dataclass is compared only with instances of its own class. It also supports field(default_factory=...), __post_init__, InitVar, inheritance with more flexibility, and per-field options such as repr=False and compare=False. A NamedTuple has none of these.
A decision flow
Dataclass versus a plain class
Write a plain class when the object is mostly behavior and its state is an implementation detail. Examples are a connection wrapper or a parser with internal buffers. Generated __eq__ and __repr__ would expose and compare state that you do not want to be part of the public contract.
Choose a dataclass when the object is mostly its fields. Its identity is its contents, and you want equality, a readable repr, and easy copying with replace().
Dataclass versus third-party libraries
Dataclasses do not check types at runtime. The annotation x: int does not stop Point("a") from working. Your own checks go in __post_init__.
from dataclasses import dataclass
@dataclass
class Age:
years: int
print(Age("forty")) # Age(years='forty'), no errorIf you need type coercion, nested parsing from JSON, or detailed error messages, a library such as pydantic fits better. attrs is a good choice when you want validators and converters, or features that predate or go beyond the standard library. The cost is a dependency and, for pydantic, extra runtime overhead on every construction. For internal data you already trust, the standard library is usually enough.
A plain dict is fine for throwaway data or data whose keys are not known in advance. Once the keys are fixed and you pass the data across several functions, a typed class catches misspelled keys earlier.
Exercises
Exercise
A function returns a latitude and longitude, and existing callers write lat, lon = locate(). Which type keeps those callers working, and why?
Show answer
A NamedTuple. It is a tuple, so it supports unpacking. A dataclass does not unpack unless you add __iter__.
Exercise
You load user records from a JSON API and need strings like "42" converted to integers, with clear errors for bad fields. Is a plain dataclass enough?
Show answer
No. Dataclasses do not coerce or check types at runtime. Use pydantic or attrs, or write the checks yourself in __post_init__.