PYTHON
Define Lightweight Data Structures with `namedtuple`
Learn to create simple, immutable objects with named fields using Python's `collections.namedtuple` for improved code readability and structured data handling.
from collections import namedtuple
# Define a namedtuple for representing a product
Product = namedtuple('Product', ['name', 'price', 'quantity'])
# Create instances of Product
product1 = Product('Laptop', 1200.00, 5)
product2 = Product(name='Mouse', price=25.50, quantity=20)
# Access fields by name or index
print(f"Product 1 Name: {product1.name}")
print(f"Product 2 Price: {product2[1]}")
# Namedtuples are immutable
try:
product1.price = 1300.00
except AttributeError as e:
print(f"Error: {e} - namedtuple instances are immutable.")
# Convert to dictionary (useful for serialization)
print(f"Product 1 as dict: {product1._asdict()}")
# Replace fields to create a new instance (since they are immutable)
product1_updated = product1._replace(price=1250.00)
print(f"Product 1 updated price: {product1_updated.price}")
How it works: `namedtuple` from the `collections` module allows you 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[0]`). They are lightweight, memory-efficient, and immutable, making them ideal for representing fixed data records like database rows or API response objects without the overhead of a full class definition. The `_asdict()` method is handy for converting an instance to a dictionary, often used for serialization.