Sub topic 12
Named Tuples for Readable Records
This chapter assumes you can create tuples, unpack them, and read a class definition with methods. A plain tuple such as (1, 2) is compact, but row[2] tells the reader nothing about what the third item means. A named tuple fixes that by giving each position a name, and it stays a real tuple.
What a named tuple is
A named tuple is a tuple subclass whose positions also have field names. You can read an item by index or by name, unpack it, compare it, hash it, and iterate over it, exactly as with any tuple.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p)
print(p.x, p[1])
x, y = p
print(x, y)
print(p == (1, 2))
print(isinstance(p, tuple))The output is:
Point(x=1, y=2)
1 2
1 2
True
FalseWait: the last line is True, not False. A Point is an instance of tuple, so isinstance(p, tuple) returns True, and the full output ends with two True lines. The repr (the text print shows) lists the field names, which makes debugging output much easier to read than a bare (1, 2).
Named tuples use no more memory per instance than plain tuples. They store no per-instance dictionary, and the field names live once on the class.
Two ways to define one
The older form is the collections.namedtuple factory function. It takes a type name and the field names, given as a list or as one string separated by spaces or commas.
from collections import namedtuple
Point = namedtuple("Point", "x y")
Color = namedtuple("Color", "red, green, blue")
print(Point(3, 4))
print(Color(255, 128, 0))The newer form is the typing.NamedTuple class syntax. It supports type annotations, default values, and methods in a normal class body.
from typing import NamedTuple
class Employee(NamedTuple):
name: str
role: str = "engineer"
salary: int = 0
def label(self):
return f"{self.name} ({self.role})"
e = Employee("Ada")
print(e)
print(e.label())
print(Employee("Grace", "admiral", 150000))The output is:
Employee(name='Ada', role='engineer', salary=0)
Ada (engineer)
Employee(name='Grace', role='admiral', salary=150000)The annotations are documentation and input for type checkers. Python does not check them at run time, so Employee(name=5) still works.
Defaults with the factory function
The factory function takes a defaults argument. Defaults apply to the rightmost fields, so with three fields and two defaults, only the first field is required.
from collections import namedtuple
Employee = namedtuple("Employee", "name role salary", defaults=["engineer", 0])
print(Employee("Ada"))
print(Employee._field_defaults)The output is:
Employee(name='Ada', role='engineer', salary=0)
{'role': 'engineer', 'salary': 0}In the class syntax, a field with a default cannot be followed by a field without one. This is the same rule as for function parameters.
Helper methods
Every named tuple class has a few underscore-prefixed members. The underscore avoids clashes with your field names. These members are public API, not private.
| Member | What it does |
|---|---|
| `_fields` | Tuple of field names |
| `_make(iterable)` | Class method that builds an instance from any iterable |
| `_asdict()` | Returns a regular `dict` of field names to values |
| `_replace(**changes)` | Returns a new instance with some fields changed |
| `_field_defaults` | Dict of default values |
from typing import NamedTuple
class Employee(NamedTuple):
name: str
role: str = "engineer"
salary: int = 0
e = Employee("Ada")
e2 = e._replace(salary=120000)
print(e2)
print(e2._asdict())
print(Employee._fields)
row = ["Grace", "admiral", 150000]
print(Employee._make(row))
print(e)The output is:
Employee(name='Ada', role='engineer', salary=120000)
{'name': 'Ada', 'role': 'engineer', 'salary': 120000}
('name', 'role', 'salary')
Employee(name='Grace', role='admiral', salary=150000)
Employee(name='Ada', role='engineer', salary=0)The last line shows that _replace did not change e. It built a new object. Because named tuples are immutable, "changing" a record always means making a modified copy.
_make is useful when data arrives as plain sequences, for example rows from the csv module or from a database cursor. Employee._make(row) is the same as Employee(*row), but it takes any iterable and reads clearly as a conversion.
Immutability still applies
Assigning to a field raises AttributeError. As with any tuple, the immutability is shallow: a mutable object stored in a field can still change.
from collections import namedtuple
Team = namedtuple("Team", "name members")
t = Team("core", ["Ada"])
try:
t.name = "platform"
except AttributeError:
print("cannot assign to a field")
t.members.append("Linus")
print(t)The output is:
cannot assign to a field
Team(name='core', members=['Ada', 'Linus'])A named tuple that holds a list is also unhashable, so it cannot be a dictionary key. Hashing works only when every field value is hashable.
Unpacking and conversion
Because a named tuple is a tuple, every unpacking form from earlier chapters works on it, including starred targets, loop targets, and * in function calls.
from collections import namedtuple
Point = namedtuple("Point", "x y z")
p = Point(1, 2, 3)
x, *rest = p
print(x, rest)
def dist_sq(x, y, z):
return x * x + y * y + z * z
print(dist_sq(*p))
points = [Point(0, 0, 1), Point(2, 0, 0)]
for px, py, pz in points:
print(px + py + pz)Unpacking ignores the field names and goes purely by position. If a record's field order changes later, code such as x, y, z = p silently gets the wrong values. When the fields matter, prefer attribute access (p.x) over positional unpacking.
To pass a named tuple's fields as keyword arguments, convert it with _asdict() and use **:
from collections import namedtuple
Point = namedtuple("Point", "x y")
def show(x, y):
print(f"x={x}, y={y}")
show(**Point(5, 6)._asdict())Gotchas
Equality ignores the type
A named tuple compares equal to any tuple with the same items, including an instance of a different named tuple type.
from collections import namedtuple
Point = namedtuple("Point", "x y")
Size = namedtuple("Size", "width height")
print(Point(1, 2) == Size(1, 2))
print(Point(1, 2) == (1, 2))Both lines print True. This follows from the tuple equality rule, which looks only at items. If you need records of different kinds to be distinct, for example as keys in one dictionary, use a dataclass (see the table below) or add the type to the key.
Field names have rules
Field names must be valid identifiers. They cannot be Python keywords, cannot begin with an underscore, and cannot repeat. Passing rename=True replaces bad names with positional ones, which is handy when the names come from external data such as a CSV header.
from collections import namedtuple
Row = namedtuple("Row", ["a", "a", "class"], rename=True)
print(Row._fields)The output is ('a', '_1', '_2').
Match the type name to the variable
The first argument to namedtuple is the class name used in repr and by pickle. Write Point = namedtuple("Point", ...) and keep the two names identical. A mismatch makes pickling fail to find the class, and it confuses readers.
Sorting follows field order
Named tuples sort like tuples, comparing the first field, then the second, and so on. Put the field you most want to sort on first, or sort with key= instead.
Choosing a structure
The right container depends on how many fields you have, whether the record must change, and how much behavior it needs.
| Need | Good choice |
|---|---|
| Two or three throwaway values, used locally | Plain tuple |
| Small fixed record, immutable, hashable, still works as a tuple | Named tuple |
| Record that must change in place, or needs `field(default_factory=...)` and distinct types | `dataclass` |
| Keys not known in advance, or data built from JSON | `dict` |
A common sign that a plain tuple has outgrown its use is a function that returns four or more values and a caller that has to remember the order. Changing the return value to a named tuple is backward compatible. Existing callers that unpack by position keep working, and new callers can use the names.
from typing import NamedTuple
class Stats(NamedTuple):
low: float
high: float
mean: float
def summarize(values):
return Stats(min(values), max(values), sum(values) / len(values))
lo, hi, avg = summarize([3, 1, 4, 1, 5])
print(lo, hi, avg)
s = summarize([3, 1, 4, 1, 5])
print(s.mean)The output is:
1 5 2.8
2.8Exercise
A function returns Version = namedtuple("Version", "major minor patch"). Write the line that creates a new Version equal to v but with patch set to 0, and say why v.patch = 0 does not work.
Show answer
Use v._replace(patch=0). It returns a new Version and leaves v unchanged. v.patch = 0 raises AttributeError because named tuples are immutable, so you cannot assign to a field.
Exercise
Given A = namedtuple("A", "x y") and B = namedtuple("B", "p q"), what does A(1, 2) == B(1, 2) return, and why?
Show answer
It returns True. Named tuples inherit tuple equality, which compares only the items and ignores the class and the field names. Use a dataclass if different record types must never compare equal.
Exercise
Using typing.NamedTuple, define Item with fields name (str), price (float) and qty (int, default 1). Then build one from the list ["pen", 1.5] and print its qty.
Show answer
Define class Item(NamedTuple): name: str; price: float; qty: int = 1 (each field on its own line), then item = Item._make(["pen", 1.5]) and print(item.qty). It prints 1, because the missing last field takes its default.