PYTHON
Define Immutable Data Structures with namedtuple
Learn to create lightweight, immutable object-like data structures using `collections.namedtuple` for clearer, self-documenting code in Python projects.
from collections import namedtuple
# Define a namedtuple for a Point (x, y coordinates)
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point coordinates: x={p1.x}, y={p1.y}")
# Define a namedtuple for a User (id, name, email)
User = namedtuple('User', 'id name email') # Can also use space-separated string
u1 = User(id=1, name='Alice', email='[email protected]')
print(f"User details: {u1.name} (ID: {u1.id}, Email: {u1.email})")
# Accessing fields by index (like a tuple)
print(f"p1[0]: {p1[0]}")
# Namedtuples are immutable, attempting to change a field raises an AttributeError
try:
p1.x = 30
except AttributeError as e:
print(f"Error: Cannot modify namedtuple field - {e}")
# Convert to dictionary
print(f"User as dict: {u1._asdict()}")
How it works: The `collections.namedtuple` factory function allows you to create tuple subclasses with named fields. This provides the immutability and memory efficiency of tuples while offering readable attribute access (e.g., `p1.x` instead of `p1[0]`). Namedtuples are ideal for creating simple, immutable data records, making code more self-documenting and less prone to errors compared to using plain tuples or custom classes for trivial data containers.