PYTHON
Defining Immutable Records with `collections.namedtuple`
Define lightweight, immutable object types using `collections.namedtuple` in Python, enhancing code readability and structure for database records, API responses, or fixed data configurations.
from collections import namedtuple
# Define a namedtuple for representing a User record
User = namedtuple('User', ['id', 'name', 'email'])
# Define a namedtuple for representing a Product record
Product = namedtuple('Product', 'product_id name price currency')
def process_user_data(user_record):
print(f"Processing User ID: {user_record.id}")
print(f"User Name: {user_record.name}")
print(f"User Email: {user_record.email}")
# user_record.name = "New Name" # This would raise an AttributeError as namedtuples are immutable
def display_product_info(product_record):
print(f"
Product Name: {product_record.name}")
print(f"Price: {product_record.price} {product_record.currency}")
# Example Usage
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"Access user1.name: {user1.name}")
print(f"Access user1[0]: {user1[0]} (like a tuple)")
process_user_data(user1)
product1 = Product(product_id='P101', name='Wireless Mouse', price=25.99, currency='USD')
product2 = Product('P102', 'Mechanical Keyboard', 89.99, 'EUR')
print(f"
Product 1: {product1}")
display_product_info(product1)
# Convert namedtuple to dictionary (useful for JSON serialization)
user1_dict = user1._asdict()
print(f"
User 1 as dict: {user1_dict}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This means you can access elements by name (e.g., `user.name`) instead of by index (e.g., `user[1]`), significantly improving code readability and maintainability. Named tuples are immutable, making them ideal for representing fixed records like database rows, API response objects, or configuration settings where data integrity is important. They are more memory-efficient than full custom classes and provide a clear, self-documenting structure for your data.