Code Snippets
/

namedtuple for Lightweight Records

namedtuple for Lightweight Records

`collections.namedtuple` produces a tuple subclass with named fields, giving you the immutability and packing of a tuple plus the readability of a dataclass. It is the right choice for tiny return-record types that should be cheap and hashable. This snippet covers the basic factory, the typed `NamedTuple` form from `typing`, and the `_replace` and `_asdict` helpers for record-style updates and JSON conversion.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
py-dataclasses

1,084 views

11

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
origin = Point(0, 0)
far = Point(3, 4)

print(origin)             # Point(x=0, y=0)
print(far.x, far.y)       # 3 4
print(far[0], far[1])     # 3 4 (still index-accessible)
print(origin == Point(0, 0))  # True (value equality)

namedtuple(name, fields) returns a class. Instances are immutable, hashable, and compare by value, just like regular tuples. Field access works either by name (pt.x) or index (pt[0]), which gives forward-compatibility with code that expected a plain tuple. The repr is informative (Point(x=0, y=0)), which beats a bare tuple in logs. Use it for tiny grouped values that pass through several layers without changing shape: coordinates, RGB triples, single rows of a parsed CSV.