| name | use-namedtuple-record |
| description | For lightweight records: immutable data with named fields, hashable structures for sets/dicts, self-documenting tuple alternatives. |
use-namedtuple-record
When to Use
- Need tuple-like efficiency with named access
- Data should be immutable
- Will use as dict keys or in sets
- Want self-documenting code
- Replacing anonymous tuples with meaning
- Coordinates, points, records
When NOT to Use
- Need mutable fields (use dataclass)
- Need methods beyond basic access
- Complex initialization logic needed
The Pattern
Use namedtuple for lightweight, immutable records with named fields.
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
p = Point(x=3, y=4)
p.x
p[0]
{p: 'origin'}
{p, q, r}
x, y = p
Example (from pytudes)
from collections import namedtuple
Point = namedtuple('Point', 'x y')
def turn(A, B, C):
"""Direction of turn A -> B -> C."""
diff = (B.x - A.x) * (C.y - B.y) - (B.y - A.y) * (C.x - B.x)
return 'right' if diff < 0 else 'left' if diff > 0 else 'straight'
Maze = namedtuple('Maze', 'width height edges')
maze = Maze(width=10, height=10, edges=set())
print(f"Maze is {maze.width}x{maze.height}")
Node = namedtuple('Node', 'state parent action path_cost')
node = Node(state=(0,0), parent=None, action=None, path_cost=0)
child = Node(state=(1,0), parent=node, action='E', path_cost=1)
Key Principles
- Immutable by design: Can't accidentally modify
- Hashable: Use in sets and as dict keys
- Memory efficient: Same as tuple, smaller than dict
- Self-documenting:
p.x beats p[0]
- Tuple compatible: Unpacking, indexing still work