PYTHON

Creating Lightweight Immutable Data Objects with `namedtuple`

Efficiently define simple, immutable data structures with named fields using Python's `collections.namedtuple` for cleaner, more readable code in web applications.

from collections import namedtuple

# Define a namedtuple for a simple API response item
Product = namedtuple('Product', ['id', 'name', 'price', 'is_available'])

# Create instances of Product
product1 = Product(id=1, name='Wireless Mouse', price=25.99, is_available=True)
product2 = Product(id=2, name='Mechanical Keyboard', price=79.99, is_available=False)

# Access fields by name or index
print(f"Product 1 Name: {product1.name}")
print(f"Product 2 Availability: {product2[3]}")

# Namedtuples are immutable (this would raise an AttributeError)
# product1.price = 29.99

# Convert to dictionary (useful for JSON serialization)
product1_dict = product1._asdict()
print(f"Product 1 as dict: {product1_dict}")

# Iterate over fields
for field, value in product1._asdict().items():
    print(f"{field}: {value}")
How it works: `namedtuple` from the `collections` module creates factory functions for tuple subclasses with named fields. This allows you to define simple, immutable data structures similar to objects but lighter weight, improving code readability by letting you access values by name instead of index. They are excellent for representing database rows, API responses, or other fixed-schema data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs