PYTHON

Define Immutable Data Records with collections.namedtuple

Use `collections.namedtuple` to create lightweight, immutable objects with named fields, enhancing code readability and data integrity for API responses or database rows.

from collections import namedtuple

# Define a namedtuple for a User record
User = namedtuple("User", ["id", "username", "email"])

# Create instances of User
user1 = User(id=1, username="alice", email="[email protected]")
user2 = User(2, "bob", "[email protected]") # Positional arguments also work

print("User 1:", user1)
print("User 2 Username:", user2.username)
print("User 1 Email:", user1[2]) # Can also access by index

# Namedtuples are immutable (this would raise an AttributeError)
# user1.username = "alicenew"

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

# Example: list of users from a database query
db_results = [
    (3, "charlie", "[email protected]"),
    (4, "diana", "[email protected]")
]
all_users = [User(*row) for row in db_results]
all_users.append(user1) # Add existing namedtuple
print("All users list:", all_users)
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields, making the code much more readable than regular tuples when representing simple data structures like database rows or API response objects. Instances are immutable, ensuring data integrity. This snippet demonstrates how to define a `User` namedtuple, create instances, access fields by name or index, and convert it to a dictionary, which is often useful for serialization in web applications. It provides a lightweight alternative to defining a full class for data-only objects.

Need help integrating this into your project?

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

Hire DigitalCodeLabs