Python Snippet

namedtuple for Lightweight Records

Difficulty: Easy

`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.

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,083 views

11

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.