PYTHON
Creating Immutable Record Types with collections.namedtuple
Improve code readability and maintainability by defining lightweight, immutable object-like data structures using Python's `collections.namedtuple` for data records.
from collections import namedtuple
# Define a namedtuple for a user record
# The first argument is the type name, the second is a string of field names (space or comma separated)
User = namedtuple('User', 'id name email signup_date')
# Create instances of the namedtuple
user1 = User(id=1, name='Alice', email='[email protected]', signup_date='2023-01-15')
user2 = User(2, 'Bob', '[email protected]', '2023-03-20') # Positional arguments also work
print(f"User 1: ID={user1.id}, Name={user1.name}, Email={user1.email}")
print(f"User 2: ID={user2[0]}, Name={user2[1]}, Email={user2[2]}") # Access by index is also possible
# namedtuples are immutable - uncommenting the line below would raise an AttributeError
# user1.name = 'Alicia'
# Convert to a dictionary (useful for serialization, e.g., to JSON)
user1_dict = user1._asdict()
print(f"User 1 as dictionary: {user1_dict}")
# Namedtuples are useful for clearer function return values
def get_product_details(product_id):
Product = namedtuple('Product', 'id name price stock')
# In a real app, this would fetch from a database
if product_id == 10:
return Product(10, 'Laptop', 1200.00, 50)
return None
product = get_product_details(10)
if product:
print(f"Product: {product.name}, Price: ${product.price}")
How it works: `collections.namedtuple` is a factory function for creating tuple subclasses with named fields. It provides a way to define lightweight, immutable object-like data structures that are more readable and self-documenting than plain tuples, and more memory-efficient than dictionaries for fixed-schema records. Instances of a `namedtuple` can be accessed by both field name and index, making them versatile for representing data records where immutability and clear field names are desired.