PYTHON
Creating Immutable Data Structures with `collections.namedtuple`
Use `collections.namedtuple` in Python to create lightweight, immutable, and self-documenting data structures, improving code readability and safety.
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}")
print(f"Point 1 X-coordinate: {p1.x}")
print(f"Point 2 Y-coordinate: {p2.y}")
# Namedtuples are immutable
try:
p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
print(f"Attempting to modify p1.x failed: {e}")
# Use namedtuple for structured database records or API responses
User = namedtuple('User', 'id name email')
user_data = User(id=1, name='Alice', email='[email protected]')
print(f"User data: {user_data.name} with email {user_data.email}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This improves code readability by allowing access to elements by name (e.g., `point.x`) instead of by index (e.g., `point[0]`). It provides immutable, lightweight objects that are useful for structured data like coordinates, database records, or API responses, preventing accidental modification and enhancing code clarity.