`namedtuple`
collections.namedtuple builds a tuple subclass with named fields. You get index access, attribute access, unpacking, and a readable repr without writing a class by hand.
Detailed Explanation
A tuple of (sku, qty, cents) is compact and easy to mix up. row[2] does not say "cents". A named tuple gives you row.cents and row[2], and row == other still compares by value. Instances are immutable: you cannot assign row.cents = 3. _replace(cents=3) returns a new instance.
namedtuple("Order", ["sku", "qty", "cents"]) returns a class. The field names must be valid identifiers and not collide with tuple methods. A string of names ("sku qty cents") is also accepted. defaults sets default values for the last n fields. module= sets __module__ so pickling and reprs look right.
The generated class has _fields, _asdict(), _replace(), and _make(iterable). Leading underscores on those helpers keep them out of the field namespace. In Python 3.7+ a _asdict() is an ordinary dict that preserves order.
typing.NamedTuple is the typed spelling: a class body with annotations. It is still a tuple under the hood. dataclasses are the usual alternative when you want methods, optional mutability, or slots without tuple inheritance. Prefer a dataclass for new application records. Prefer a named tuple when you need to be a tuple (unpacking, memory, compatibility with APIs that already return tuples).
Because they are tuples, named tuples are hashable if their fields are. They can be dict keys. They compare equal to plain tuples with the same values: Order("A-1", 1, 100) == ("A-1", 1, 100) is True. That is convenient and can hide a type mix-up.
Code Examples
from collections import namedtuple
Order = namedtuple("Order", ["sku", "qty", "cents"], defaults=[1, 0])
line = Order("A-1", 2, 2500)
print(line.sku, line[0]) # A-1 A-1
print(line._asdict()) # {'sku': 'A-1', 'qty': 2, 'cents': 2500}
print(line._replace(qty=3).qty) # 3from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(3, 4)
print(p.x, p[1], p == (3, 4)) # 3 4 True# Unpacking still works.
sku, qty, cents = Order("B-2", 1, 400)
print(sku, cents) # B-2 400Common Gotchas
Instances are immutable
`line.qty = 2` raises `AttributeError`. Use `_replace`.
Equality with plain tuples
`namedtuple == tuple` can be true, so `isinstance` or an explicit type check if the distinction matters.
Field names can clash
`count` and `index` already exist on tuple. Pick other names, or pass `rename=True` and accept generated names.
New code often wants a dataclass
use `namedtuple` when tuple-ness is a feature, not from habit.