PYTHON
Define Structured, Immutable Records with namedtuple
Create lightweight, self-documenting data structures with `collections.namedtuple` in Python, ideal for immutable records like API responses or database rows.
from collections import namedtuple
# Define a namedtuple for a User
User = namedtuple('User', ['id', 'username', 'email'])
# Create instances
user1 = User(id=1, username='alice', email='[email protected]')
user2 = User(id=2, username='bob', email='[email protected]')
print(f"User 1 ID: {user1.id}, Username: {user1.username}")
print(f"User 2 Email: {user2.email}")
# Accessing elements like a tuple (by index)
print(user1[0]) # Output: 1
# namedtuples are immutable
# user1.id = 3 # This would raise an AttributeError
How it works: This snippet shows how to use `collections.namedtuple` to create simple, immutable data structures. `namedtuple` instances are like tuples but allow accessing elements by name in addition to index, making the code more readable and self-documenting. They are particularly useful for representing records where the data fields are known, such as database query results or API responses, providing a more structured alternative to plain tuples or dictionaries.