PYTHON
Creating Immutable Data Objects with Python's collections.namedtuple
Define lightweight, immutable data structures with named fields using collections.namedtuple for cleaner, more readable code and improved data integrity in Python.
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"Point 2: {p2}")
# Accessing fields by name (more readable than index)
print(f"p1.x: {p1.x}, p1.y: {p1.y}")
# Accessing fields by index (like a regular tuple)
print(f"p2[0]: {p2[0]}, p2[1]: {p2[1]}")
# Namedtuples are immutable (this would raise an AttributeError)
# try:
# p1.x = 15
# except AttributeError as e:
# print(f"Error: {e}")
# Convert namedtuple to a dictionary (useful for serialization)
print(f"p1 as dict: {p1._asdict()}")
# Define another namedtuple for a User
User = namedtuple('User', 'id name email')
user1 = User(1, 'Alice', '[email protected]')
print(f"User 1: {user1.name}, Email: {user1.email}")
How it works: The `collections.namedtuple` factory function allows you to create tuple subclasses with named fields. This means you can access values by name (e.g., `point.x`) instead of generic integer indices (e.g., `point[0]`), which greatly improves code readability and maintainability. Namedtuples are lightweight, immutable, and consume less memory than a full class instance, making them ideal for defining simple data records where you want structured, self-documenting data without the overhead of a full custom class definition.