PYTHON
Creating Readable Data Records with `collections.namedtuple`
Structure your data with improved readability and immutability using Python's `collections.namedtuple`, ideal for representing database rows or API responses.
from collections import namedtuple
# Define a namedtuple for User data
# The first argument is the tuple name, second is a string of space-separated field names
User = namedtuple('User', 'id name email role')
# Create instances of User
user1 = User(id=1, name='Alice', email='[email protected]', role='admin')
user2 = User(id=2, name='Bob', email='[email protected]', role='editor')
print(f"User 1: {user1}")
print(f"User 2: {user2}")
# Access fields by name (more readable than index)
print(f"
User 1's name: {user1.name}")
print(f"User 2's email: {user2.email}")
# Access fields by index (like a regular tuple)
print(f"User 1's role (by index): {user1[3]}")
# Namedtuples are immutable (like regular tuples)
try:
user1.role = 'guest'
except AttributeError as e:
print(f"
Error trying to modify namedtuple: {e}")
# Convert to dictionary (useful for serialization, e.g., to JSON)
user1_dict = user1._asdict()
print(f"User 1 as dict: {user1_dict}")
# Create from an iterable (e.g., a database row)
user_data_from_db = (3, 'Charlie', '[email protected]', 'viewer')
user3 = User._make(user_data_from_db)
print(f"User 3 from iterable: {user3}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This enhances code readability by letting you access elements using descriptive names (e.g., `user.name`) instead of ambiguous integer indices (e.g., `user[1]`). It's perfect for representing immutable data records, such as database rows, API response objects, or configuration settings, providing the immutability and efficiency of tuples with the clarity of object attributes. The snippet also shows how to convert a namedtuple to a dictionary, useful for JSON serialization.