PYTHON
Create Immutable, Self-Documenting Data Records with `namedtuple`
Enhance code readability and maintainability by using `collections.namedtuple` to define lightweight, immutable object-like data structures. Access fields by name or index.
from collections import namedtuple
# Define a namedtuple type for a Product
# 'Product' is the name of the new class
# ['name', 'price', 'quantity'] are the field names
Product = namedtuple('Product', ['name', 'price', 'quantity'])
# Create instances of the Product
product1 = Product('Laptop', 1200.00, 10)
product2 = Product('Mouse', 25.50, 50)
# Access fields by name (more readable)
print(f"Product 1 Name: {product1.name}")
print(f"Product 1 Price: ${product1.price:.2f}")
# Access fields by index (less common but possible)
print(f"Product 2 Quantity: {product2[2]}")
# Namedtuples are immutable (cannot change values after creation)
# The following line would raise an AttributeError:
# product1.price = 1150.00
# Convert to dictionary (useful for serialization, e.g., JSON)
product1_dict = product1._asdict()
print(f"Product 1 as dict: {product1_dict}")
How it works: `collections.namedtuple` provides a factory function for creating tuple subclasses with named fields. This allows you to create immutable, lightweight objects where fields can be accessed by name (e.g., `product.name`) instead of just by index (e.g., `product[0]`), significantly improving code readability and maintainability. They are more memory-efficient than a full custom class for simple data structures and are ideal for situations where you need to group related data without requiring methods or mutable state. The `_asdict()` method is handy for converting a `namedtuple` instance into a dictionary, often useful for serialization.