PYTHON
Creating Immutable Data Records with `collections.namedtuple`
Learn to use Python's `collections.namedtuple` to create lightweight, immutable objects with named fields, enhancing code readability and data access.
from collections import namedtuple
# Define a named tuple type for representing a point
Point = namedtuple('Point', ['x', 'y'])
# Create instances of the named tuple
p1 = Point(10, 20)
p2 = Point(y=30, x=5)
print(f"Point 1: x={p1.x}, y={p1.y}")
print(f"Point 2: x={p2[0]}, y={p2[1]}") # Access by index also works
# Named tuples are immutable
try:
p1.x = 15
except AttributeError as e:
print(f"
Error trying to modify named tuple: {e}")
# Convert to dictionary
print("
Point 1 as dictionary:", p1._asdict())
# Replace fields (creates a new named tuple instance)
p3 = p1._replace(x=15)
print(f"Point 3 (from p1._replace): x={p3.x}, y={p3.y}")
How it works: `collections.namedtuple` provides an easy way to create simple, immutable classes similar to a tuple, but with named fields. This improves code readability by allowing access to elements using descriptive names (e.g., `point.x`) instead of numerical indices (e.g., `point[0]`). They are lightweight, memory-efficient, and useful for creating data records where immutability and clear field names are desired, without the overhead of defining a full custom class.