PYTHON

Create Lightweight Data Objects with Python Namedtuple

Utilize Python's collections.namedtuple to define simple, immutable objects with named fields, offering clarity over regular tuples and efficiency over full classes.

from collections import namedtuple

# Define a namedtuple for representing API response data (e.g., a product)
Product = namedtuple('Product', ['id', 'name', 'price', 'category'])

# Define a namedtuple for representing user session data
SessionInfo = namedtuple('SessionInfo', ['user_id', 'timestamp', 'ip_address'])

def fetch_product_details(product_id):
    """
    Simulates fetching product details and returning them as a namedtuple.
    """
    # In a real app, this would query a database or external API
    if product_id == 101:
        return Product(id=101, name="Wireless Mouse", price=25.99, category="Electronics")
    return None

def create_session(user_id, ip_address):
    """
    Creates a session info record using namedtuple.
    """
    import datetime
    return SessionInfo(user_id=user_id, timestamp=datetime.datetime.now(), ip_address=ip_address)

# Example usage for a web application scenario
product = fetch_product_details(101)
if product:
    print(f"Product Name: {product.name}, Price: ${product.price:.2f}")
    # Access by index also works: print(product[1])
    # namedtuples are immutable: product.price = 30.00 # This would raise an AttributeError

session = create_session(user_id=42, ip_address="192.168.1.100")
print(f"User {session.user_id} logged in from {session.ip_address} at {session.timestamp}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides the readability of object attribute access (e.g., `product.name`) while retaining the memory efficiency and immutability of tuples. It's excellent for returning structured but lightweight data from functions or API endpoints without defining full classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs