Sub topic 12
Named Tuples for Readable Records
This chapter assumes you can create and unpack tuples, index and slice them, and write simple classes and functions. You should also know that tuples are immutable.
The problem with plain tuples
A plain tuple identifies its items by position only. Code like row[2] tells the reader nothing about what the third item means. A named tuple fixes this. It is still a tuple, but each position also has a field name.
Creating a named tuple
collections.namedtuple builds a new class from a type name and a list of field names.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
x, y = p
print(p.x, p.y, x, y)
print(p == (1, 2))Point is a class, and p is an instance of it. You can read fields by name (p.x), by index (p[0]), or by unpacking (x, y = p). The comparison p == (1, 2) is True because a named tuple compares like an ordinary tuple.
You can also create instances with keyword arguments, such as Point(y=2, x=1). Python matches the keywords to field names, so the order you write them in does not matter.
The class-based form
typing.NamedTuple gives the same result with class syntax. It adds type hints and default values, and it lets you write docstrings and methods.
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float = 0.0
p = Point(1)
print(p)
q = p._replace(y=5)
print(q)
print(q._asdict())
print(Point._fields)This prints Point(x=1, y=0.0), then Point(x=1, y=5), then {'x': 1, 'y': 5}, then ('x', 'y'). Fields with defaults must come after fields without them, as with function parameters.
The helper methods start with an underscore to avoid clashing with your field names. They are still public.
_replace(**changes)returns a new instance with some fields changed._asdict()returns a dictionary of field names and values._fieldsis a tuple of the field names.
Still immutable
Named tuples keep the tuple's immutability. Assigning to a field raises AttributeError.
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(1, 2)
try:
p.x = 10
except AttributeError:
print("fields cannot be reassigned")
print(p._replace(x=10))_replace does not change p. It builds a new object. The same caveat from earlier applies as well. If a field holds a list, that list can still change. A named tuple is hashable only if all of its fields are hashable, so it works as a dictionary key under the same rules as a plain tuple.
Common errors
- Wrong name for the type. The first argument to
namedtupleis only the class's name. By convention it matches the variable you assign to. If the two differ, printed output and error messages show the string, not your variable name. - Cross-type equality. Equality ignores the class. Two named tuples of different types are equal when their values match.
from collections import namedtuple
Point = namedtuple("Point", "x y")
Size = namedtuple("Size", "w h")
print(Point(1, 2) == Size(1, 2))This prints True, which can hide bugs when you compare records of different kinds. If that matters, use a dataclass instead.
- Unpacking by position. Unpacking ignores field names, so
y, x = psilently swaps the values. Check the field order before you unpack.
Choosing a structure
| Structure | Best when | Mutable | Fixed fields |
|---|---|---|---|
| Plain tuple | Short, obvious groups such as `(x, y)` | No | By position |
| Named tuple | Small, read-only records that need names, or tuple compatibility | No | Yes |
| Dataclass | Records that need changing, validation, or strict type identity | Yes (by default) | Yes |
| Dictionary | Keys that vary at runtime | Yes | No |
A named tuple is a good upgrade for a function that returns three or more values. Callers can unpack the result as before or read fields by name. Code that already treats the result as a tuple keeps working.
Exercise
Define a named tuple Temp with fields city and celsius. Create t = Temp("Oslo", 4). Then produce a new record with celsius set to 7 without changing t, and print both.
Show answer
from typing import NamedTuple class Temp(NamedTuple): city: str celsius: float t = Temp("Oslo", 4) u = t.replace(celsius=7) print(t) print(u) This prints Temp(city='Oslo', celsius=4) and then Temp(city='Oslo', celsius=7). The original is unchanged because replace returns a new instance.