PYTHON

Define Immutable Data Structures with Python Named Tuples

Leverage collections.namedtuple in Python to create simple, immutable objects with named fields, perfect for structured data returns, database records, or configuration.

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) # Can also pass arguments positionally

print(f"User 1: {user1}")
print(f"User 2: {user2}")

# Access fields by name (like an object)
print(f"User 1's username: {user1.username}")
print(f"User 2's email: {user2.email}")

# Access fields by index (like a tuple)
print(f"User 1's ID: {user1[0]}")

# Named tuples are immutable (uncommenting the line below will raise an AttributeError)
# user1.is_active = False # This will cause an error

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

# Replace specific fields (returns a new namedtuple instance)
user1_updated = user1._replace(is_active=False, email='[email protected]')
print(f"User 1 updated: {user1_updated}")
print(f"Original user1 remains: {user1}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides a way to define lightweight, immutable object-like data structures without the full overhead of defining a class. Fields can be accessed by name (e.g., `user.username`) or by index (e.g., `user[1]`). Named tuples are memory-efficient and, being immutable, are safe for use as dictionary keys or in scenarios where data integrity is critical. They are excellent for returning structured query results, API responses, or temporary data records in web development.

Need help integrating this into your project?

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

Hire DigitalCodeLabs