PYTHON
Create Lightweight Immutable Data Containers with namedtuple
Define simple, immutable objects with named fields using Python's collections.namedtuple. Enhances code readability and reduces errors compared to plain tuples or dicts.
from collections import namedtuple
# Define a namedtuple type for a Point
# 'Point' is the class name, ['x', 'y'] are the field names
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40) # Can use keyword arguments too
print(f"Point 1: {p1}")
print(f"Point 2: {p2}")
# Accessing fields by name (improves readability)
print(f"Point 1 X coordinate: {p1.x}")
print(f"Point 2 Y coordinate: {p2.y}")
# Can still access by index (like a regular tuple)
print(f"Point 1 Y coordinate by index: {p1[1]}")
# namedtuple instances are immutable
# p1.x = 50 # This line would raise an AttributeError if uncommented
# Convert to dictionary
p1_dict = p1._asdict()
print(f"Point 1 as dictionary: {p1_dict}")
How it works: `collections.namedtuple` provides a concise way to create simple, immutable object types with named fields. Instead of accessing elements by integer index (e.g., `my_tuple[0]`), you can use descriptive attribute names (e.g., `my_object.field_name`), significantly improving code readability and maintainability. They behave much like regular tuples, offering immutability and memory efficiency, but with the added benefit of self-documenting field access.