Python Glossary Русский

all Python 3collectionsterm

collections.namedtuple

namedtuple

Creates a subclass of tuple with named fields. It supports _replace() (a copy with some fields changed) and _asdict() (conversion to a dictionary).

Syntax

collections.namedtuple(typename, field_names)

It really is a tuple, so Point(1, 2) == (1, 2) is True and the fields unpack and iterate like tuple items — handy, but it means accidental equality with a plain tuple. The values are frozen: _replace() hands back a new object instead of editing the old one. The leading underscores on the helper methods exist so they cannot collide with your own field names; if you need mutability, defaults or methods, reach for a dataclass instead.

Examples

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)  # → 1 2
print(p._asdict())  # → {'x': 1, 'y': 2}
p2 = p._replace(x=10)  # → Point(x=10, y=2)
print(p2)  # → Point(x=10, y=2)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy