PYTHON
Create Readable Data Records with `collections.namedtuple`
Improve code readability and maintainability by defining lightweight, immutable object-like data records using Python's `collections.namedtuple` for structured data.
from collections import namedtuple
# Define a namedtuple for a product record
Product = namedtuple('Product', ['id', 'name', 'price', 'in_stock'])
# Create instances of Product
product1 = Product(id=101, name='Laptop', price=1200.00, in_stock=True)
product2 = Product(id=102, name='Mouse', price=25.50, in_stock=False)
product3 = Product(103, 'Keyboard', 75.00, True) # Positional arguments also work
# Access fields by name (more readable than tuple indices)
print(f"Product 1 Name: {product1.name}")
print(f"Product 2 Price: {product2.price}")
print(f"Product 3 Stock Status: {product3.in_stock}")
# Namedtuples are immutable
try:
product1.price = 1250.00
except AttributeError as e:
print(f"Attempting to modify a namedtuple field raises an error: {e}")
# Namedtuples can be iterated like regular tuples
for value in product1:
print(value, end=" ")
print()
# Convert to dictionary if needed
print(f"Product 1 as dict: {product1._asdict()}")
How it works: `collections.namedtuple` is used to create tuple subclasses with named fields. This enhances code readability by allowing access to elements using descriptive names (e.g., `product.name`) instead of integer indices (e.g., `product[1]`). `namedtuple` instances are immutable, providing a lightweight, memory-efficient way to represent structured data records, ideal for API responses, database rows, or simple object-like data without the overhead of a full class definition.