PYTHON
Define Immutable, Readable Data Records with `collections.namedtuple`
Enhance code readability by using `collections.namedtuple` to create lightweight, immutable object-like tuples, providing attribute access for structured data without full class definitions.
from collections import namedtuple
# Define a namedtuple for representing a Point
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
# Access elements by name (more readable than index)
print(f"Point 1: x={p1.x}, y={p1.y}")
print(f"Point 2: x={p2.x}, y={p2.y}")
# Still accessible by index, like a regular tuple
print(f"Point 1 (by index): x={p1[0]}, y={p1[1]}")
# Namedtuples are immutable
try:
p1.x = 15
except AttributeError as e:
print(f"Attempting to modify p1.x: {e}")
# Convert namedtuple to a dictionary (useful for serialization)
print(f"Point 1 as dict: {p1._asdict()}")
# Another example: Employee record
Employee = namedtuple('Employee', 'name age department salary')
employee1 = Employee('Alice', 30, 'HR', 60000)
print(f"Employee 1: {employee1.name} works in {employee1.department}")
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 making your code more readable by allowing you to access elements by attribute name instead of integer index. It's ideal for defining simple, immutable data structures without the overhead of a full class definition, enhancing clarity and reducing potential errors in data access.