PYTHON

Creating Immutable, Self-Documenting Data Objects

Utilize collections.namedtuple to create lightweight, immutable object types with named fields, improving code readability and data integrity in Python.

from collections import namedtuple

# Define a Point data structure
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)

print(f"Point p1: {p1}")
print(f"X coordinate: {p1.x}")
print(f"Y coordinate: {p1.y}")

# Access by index (like a tuple)
print(f"Point by index: {p1[0], p1[1]}")

# namedtuples are immutable
try:
    p1.x = 30
except AttributeError as e:
    print(f"Error trying to modify: {e}")

# Useful for returning structured data from functions
def get_user_info(user_id):
    User = namedtuple('User', ['id', 'username', 'email'])
    # In a real app, this would fetch from a DB
    if user_id == 1:
        return User(id=1, username="alice", email="[email protected]")
    return None

user = get_user_info(1)
if user:
    print(f"User info: ID={user.id}, Username={user.username}")

# Convert to dictionary
print(f"User as dict: {user._asdict()}")
How it works: collections.namedtuple is a factory function for creating tuple subclasses with named fields. It allows you to create simple, immutable data objects where each item can be accessed by both its index (like a regular tuple) and its name (like a dictionary or object attribute). This improves code readability and reduces errors compared to using plain tuples, especially when dealing with structured data from APIs or databases.

Need help integrating this into your project?

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

Hire DigitalCodeLabs