PYTHON
Create Lightweight Data Records with `collections.namedtuple`
Define simple, immutable data structures with named fields using Python's `collections.namedtuple`, ideal for clear API responses or configuration objects in web apps.
from collections import namedtuple
# Define a namedtuple for representing a product
Product = namedtuple("Product", ["id", "name", "price", "stock"])
# Create product instances
product1 = Product(id=1, name="Laptop", price=1200.00, stock=50)
product2 = Product(id=2, name="Mouse", price=25.50, stock=200)
print(f"Product 1 Name: {product1.name}")
print(f"Product 2 Price: {product2.price}")
# Namedtuples are immutable
try:
product1.price = 1250.00
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}")
# Example: Representing a simplified user session object
Session = namedtuple("Session", "user_id last_login ip_address")
user_session = Session(user_id="user123", last_login="2023-10-27T10:30:00Z", ip_address="192.168.1.100")
print(f"User Session IP: {user_session.ip_address}")
# Can convert to dictionary if needed
print(f"Product 1 as dict: {product1._asdict()}")
How it works: This snippet demonstrates `collections.namedtuple`, a factory function for creating tuple subclasses with named fields. It provides an easy way to create immutable, self-documenting data structures that are more readable than plain tuples and less verbose than full classes. In web development, namedtuples are excellent for structuring data from API responses, representing database query results, or defining lightweight configuration objects, improving code clarity and maintainability.