PYTHON
Define Readable, Immutable Data Records with namedtuple
Improve code clarity and prevent accidental modifications by using Python's collections.namedtuple to create lightweight, immutable object-like data structures for fixed-schema data.
from collections import namedtuple
# Define a namedtuple type for a database record or API response
# The first argument is the name of the tuple, the second is a string of field names
# separated by spaces or a list of strings
User = namedtuple('User', 'id name email')
# Create instances of the namedtuple
user1 = User(id=1, name='Alice', email='[email protected]')
user2 = User(id=2, name='Bob', email='[email protected]')
print(f"User 1: {user1}")
print(f"User 2 email: {user2.email}")
# Access fields by name (more readable than index)
print(f"User 1 ID: {user1.id}")
# namedtuples are immutable (attempting to change will raise AttributeError)
try:
user1.name = 'Alicia'
except AttributeError as e:
print(f"Cannot modify namedtuple: {e}")
# They behave like tuples, so you can unpack them
id, name, email = user1
print(f"Unpacked user: {name} ({email})")
# Convert namedtuple to a dictionary (useful for serialization)
user_dict = user1._asdict()
print(f"User 1 as dict: {user_dict}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides a more readable and self-documenting way to store data records compared to plain tuples or dictionaries, where accessing elements by index or string keys can be error-prone. Named tuples are immutable, ensuring that once created, their values cannot be changed, which is beneficial for data integrity and preventing unintended side effects in your web application logic.