PYTHON
Creating Immutable, Lightweight Data Objects with collections.namedtuple
Discover how collections.namedtuple provides an easy way to create custom object types with named fields, offering immutability and readability without full class boilerplate.
from collections import namedtuple
# Define a named tuple for a Point
Point = namedtuple('Point', ['x', 'y'])
# Create instances
p1 = Point(10, 20)
p2 = Point(y=5, x=15)
print(f"Point 1: {p1}, x={p1.x}, y={p1.y}")
print(f"Point 2: {p2}, x={p2.x}, y={p2.y}")
# Access elements by index (like a tuple)
print(f"Point 1 (index 0): {p1[0]}")
# Named tuples are immutable (this would raise an AttributeError if uncommented)
# p1.x = 30
# Convert to dictionary (useful for serialization)
print(f"Point 1 as dictionary: {p1._asdict()}")
# Iterate over fields
for coord in p1:
print(coord)
How it works: collections.namedtuple is a factory function for creating tuple subclasses with named fields. It allows you to create simple, immutable data objects that are more readable than plain tuples, as you can access elements by name (e.g., point.x) instead of just by index. They are lightweight, memory-efficient, and useful for defining clear data structures without the overhead of defining a full class, making them great for representing database rows or API responses.