← Back to all snippets
PYTHON

Representing Immutable Data Records with collections.namedtuple

Learn how to use Python's collections.namedtuple to create lightweight, immutable objects for structured data, improving code readability and reducing errors in web applications.

from collections import namedtuple

# Define a namedtuple for a User profile
UserProfile = namedtuple('UserProfile', ['id', 'username', 'email', 'is_active'])

# Create instances of UserProfile
user1 = UserProfile(id=1, username='alice_smith', email='[email protected]', is_active=True)
user2 = UserProfile(2, 'bob_johnson', '[email protected]', False) # Positional arguments also work

# Access data using attribute names
print(f"User 1: {user1.username}, Email: {user1.email}, Active: {user1.is_active}")

# Namedtuples are immutable
try:
    user1.username = 'new_alice'
except AttributeError as e:
    print(f"Error trying to modify: {e}")

# Convert to dictionary if needed (e.g., for JSON serialization)
user1_dict = user1._asdict()
print(f"User 1 as dict: {user1_dict}")

# Use cases: API responses, database records, configuration settings
def process_user_data(user: UserProfile):
    if user.is_active:
        print(f"Processing active user: {user.username}")

process_user_data(user1)
How it works: collections.namedtuple allows creating tuple subclasses with named fields. This enhances code readability by letting you access elements using attribute names (e.g., user.username) instead of integer indices (e.g., user[1]), making code more self-documenting. Named tuples are immutable, providing data integrity, and are useful for representing fixed data structures like database rows, API response objects, or configuration settings. They are more memory-efficient than full custom classes for simple data aggregation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs