PYTHON
Create Immutable Data Records with Python's namedtuple
Enhance code readability and maintainability by using `collections.namedtuple` to define simple, immutable objects with named fields, perfect for structured data.
from collections import namedtuple
# Define a namedtuple for a Point
# It acts like an immutable class with defined fields
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 Point 1: {p1.x}")
print(f"Y coordinate of Point 2: {p2.y}")
# Access fields by index (like a tuple)
print(f"Point 1 (by index): {p1[0]}, {p1[1]}")
# Namedtuples are immutable (attempting to change raises an error)
try:
p1.x = 15
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}")
# Convert to dictionary
point_dict = p1._asdict()
print(f"Point 1 as dictionary: {point_dict}")
How it works: `collections.namedtuple` provides a way to create lightweight, immutable object types. It's essentially a factory function for creating tuple subclasses with named fields. This improves code readability by allowing access to elements by name (e.g., `point.x`) instead of generic indices (e.g., `point[0]`), while retaining the memory efficiency and immutability of regular tuples. It's ideal for defining simple data structures where a full class definition might be overkill.