PYTHON
Create Lightweight, Self-Documenting Data Structures with `NamedTuple`
Leverage `collections.namedtuple` to define tuple subclasses with named fields, offering immutability, readability, and object-like access to structured data without the overhead of a full class.
from collections import namedtuple
# Define a NamedTuple for a Point
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point p1: {p1}")
print(f"X coordinate: {p1.x}, Y coordinate: {p1.y}")
# NamedTuple for a User record
User = namedtuple('User', 'id name email')
user1 = User(id=1, name="Alice", email="[email protected]")
user2 = User(2, "Bob", "[email protected]") # Positional arguments also work
print(f"User 1: {user1}")
print(f"User 2 name: {user2.name}")
# Accessing fields by index (like a regular tuple)
print(f"User 1 ID by index: {user1[0]}")
# NamedTuples are immutable
try:
user1.name = "Alicia"
except AttributeError as e:
print(f"Error trying to modify a namedtuple field: {e}")
# Convert namedtuple to a dictionary
user_dict = user1._asdict()
print(f"User 1 as dict: {user_dict}")
# Create new namedtuple instances with modifications (immutably)
user1_updated_email = user1._replace(email="[email protected]")
print(f"User 1 with updated email: {user1_updated_email}")
print(f"Original User 1 remains unchanged: {user1}")
How it works: `collections.namedtuple` is a factory function for creating tuple subclasses with named fields. It allows you to access elements by their names (e.g., `point.x`) instead of just by index (e.g., `point[0]`), significantly improving code readability and maintainability for structured, immutable data. They are lighter than full-blown classes, making them suitable for representing records or API responses where data integrity is important and modifications are handled by creating new instances.