PYTHON
Create Immutable Structured Data with collections.namedtuple
Enhance code readability and maintainability by using collections.namedtuple to define lightweight, immutable object-like structures for database records, API responses, or configuration.
from collections import namedtuple
# Define a namedtuple for a User
User = namedtuple('User', ['id', 'username', 'email'])
# Create user instances
user1 = User(id=1, username='alice', email='[email protected]')
user2 = User(id=2, username='bob', email='[email protected]')
print(f"User 1: {user1}")
print(f"User 1's username: {user1.username}")
# Namedtuples are immutable (attempting to change raises AttributeError)
try:
user1.username = 'alicia'
except AttributeError as e:
print(f"Cannot modify namedtuple fields: {e}")
# Can be used to unpack sequences
user_data = (3, 'charlie', '[email protected]')
user3 = User._make(user_data) # Alternative to User(*user_data)
print(f"User 3: {user3}")
# Convert to dictionary
print(f"User 2 as dict: {user2._asdict()}")
How it works: collections.namedtuple allows you to create tuple subclasses with named fields. This significantly improves code readability compared to using plain tuples (e.g., user.username instead of user[1]). They are lightweight and immutable, making them excellent for representing structured records like database rows, API payload objects, or configuration settings where immutability is desirable.