Named fields make tuples returned from functions or read from CSV files self-documenting.
namedtuple creates a tuple subclass with named fields:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x, p[1] # 3, 4Because it is a tuple, a namedtuple is immutable, hashable (if its contents are), unpackable (x, y = p), comparable, and as memory-efficient as a plain tuple: there's no per-instance __dict__. Its repr shows the field names, which makes debugging output readable.
Useful extras (names start with an underscore to avoid clashing with fields):
p._replace(x=10)returns a copy with some fields changed.p._asdict()returns a dict of fields.Point._fieldslists the field names;Point._make(iterable)builds from a sequence, handy for CSV rows.namedtuple("P", "x y", defaults=[0])gives defaults to the rightmost fields.
Field names can be given as a list or a space/comma separated string. rename=True replaces invalid names (like keywords) with positional names.
The typed equivalent is typing.NamedTuple with class syntax and annotations. For mutable records or records with methods and validation, dataclasses is usually a better fit.
Example
import csv
import io
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p) # Point(x=3, y=4)
print(p.x + p[1]) # 7
x, y = p
print(p._replace(y=0)) # Point(x=3, y=0)
print(p._asdict()) # {'x': 3, 'y': 4}
rows = io.StringIO("name,qty\napple,3\npear,5\n")
reader = csv.reader(rows)
Item = namedtuple("Item", next(reader))
items = [Item._make(r) for r in reader]
print(items[1].name, items[1].qty) # pear 5
Config = namedtuple("Config", "host port debug", defaults=[8000, False])
print(Config("localhost")) # Config(host='localhost', port=8000, debug=False)Remember
- namedtuple adds field names to an immutable, lightweight tuple
_replace,_asdict,_fieldsand_makecover common needs- Use typing.NamedTuple for type hints, dataclasses for mutable records
Watch out for
- Trying
p.x = 5; namedtuples are immutable, so use_replace.