PYTHON
Create Immutable, Readable Data Records with `collections.namedtuple`
Utilize `collections.namedtuple` to define custom tuple subclasses with named fields, enhancing code readability and making data access clearer than with regular tuples.
from collections import namedtuple
# Define a namedtuple for a point
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point p1: {p1}")
print(f"Accessing x: {p1.x}, Accessing y: {p1.y}")
# Namedtuple for a product record
Product = namedtuple('Product', 'id name price stock')
product1 = Product(id='P001', name='Laptop', price=1200.00, stock=50)
product2 = Product('P002', 'Mouse', 25.00, 200)
print(f"Product 1 name: {product1.name}")
print(f"Product 2 price: {product2.price}")
# Namedtuples are immutable
# product1.stock = 45 # This would raise an AttributeError
How it works: `collections.namedtuple` is a factory function that allows you to create tuple subclasses with named fields. Instead of accessing elements by numerical index (e.g., `item[0]`), you can access them by name (e.g., `item.name`), significantly improving code readability and self-documentation, especially when dealing with structured data records. Namedtuples are immutable, which means their contents cannot be changed after creation, making them safe for use in contexts like dictionary keys or multi-threaded environments.