PYTHON
Creating Readable Immutable Data Records with `collections.namedtuple`
Enhance code readability and maintainability by using Python's `collections.namedtuple` to define simple, immutable objects with named fields.
from collections import namedtuple
# Define a namedtuple for a Point
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
print(f"Point 1: {p1}")
print(f"X coordinate of p1: {p1.x}")
print(f"Y coordinate of p2: {p2.y}")
# Namedtuples are immutable
try:
p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}")
# Can convert to dictionary
print(f"P1 as dict: {p1._asdict()}")
# Expected output:
# Point 1: Point(x=10, y=20)
# X coordinate of p1: 10
# Y coordinate of p2: 40
# Error trying to modify namedtuple: can't set attribute
# P1 as dict: {'x': 10, 'y': 20}
How it works: `collections.namedtuple` creates factory functions for tuple subclasses that have named fields. This allows accessing elements by name (e.g., `point.x`) instead of by index (e.g., `point[0]`), significantly improving code readability for structured, immutable data, while retaining the memory efficiency of tuples.