PYTHON
Creating Self-Documenting Data Records with Python `namedtuple`
Enhance code readability and maintainability by using Python's `collections.namedtuple` to create lightweight, immutable objects for structured data, accessible by name and index.
from collections import namedtuple
# Define a namedtuple for a Point
# The first argument is the type name, the second is a string of field names
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
p3 = Point(y=50, x=60) # Order doesn't matter with keyword arguments
print(f"Point p1: {p1}")
print(f"Point p2: {p2}")
# Access fields by name (readable and preferred)
print(f"p1.x: {p1.x}, p1.y: {p1.y}")
# Access fields by index (like a regular tuple)
print(f"p2[0]: {p2[0]}, p2[1]: {p2[1]}")
# Namedtuples are immutable
try:
p1.x = 15
except AttributeError as e:
print(f"Error trying to modify p1.x: {e}")
# Namedtuples can be converted to dictionaries
print(f"p3 as dictionary: {p3._asdict()}")
# Iterate over fields
for value in p1:
print(f"Coordinate: {value}")
# Example with more fields
City = namedtuple('City', 'name country population area_sq_km')
london = City('London', 'UK', 8900000, 1572)
print(f"
City object: {london}")
print(f"City name: {london.name}, Country: {london.country}")
How it works: `collections.namedtuple` provides a factory function for creating tuple subclasses with named fields. This allows you to create lightweight, immutable objects similar to structs or records in other languages, where values can be accessed both by index and by descriptive field names. This improves code readability and reduces the chance of errors compared to using plain tuples (where you'd remember index meanings) or dictionaries (which are mutable and heavier for simple fixed-schema records). The snippet demonstrates defining a `namedtuple` type, creating instances, accessing fields by name and index, highlighting their immutability, and showing utility methods like `_asdict()` for conversion to a dictionary.