Python 3.5+Annotations & typingterm
typing.NamedTuple
namedtuple
A typed named tuple defined by inheritance. Class syntax with annotations.
Syntax
from typing import NamedTuple
class MyTuple(NamedTuple):
field: type
Reach for NamedTuple when you want an immutable, hashable record that still behaves like a tuple: unpacking, indexing, use as a dict key, small memory footprint. If the fields have to change, or you need inheritance and custom behaviour, a dataclass fits better. The trap is that it really is a tuple: Point(1.0, 2.0) == (1.0, 2.0) is True, so the type will not protect you from mixing it up with plain tuples. The functional form NamedTuple('NT', x=int) with keyword arguments, and a call without a field list, were deprecated in 3.13 and are disallowed from 3.15: write a class as in the example, or NamedTuple('NT', [('x', int)]).
Examples
from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float
label: str = ''
p = Point(1.0, 2.0, 'A')
print(p.x) # → 1.0
print(p.label) # → A
print(p._asdict()) # → {'x': 1.0, 'y': 2.0, 'label': 'A'}
print(p._replace(x=5.0)) # → Point(x=5.0, y=2.0, label='A')
See also
Open in the full glossarydocs.python.orgReport an inaccuracy