PYTHON
Readable Data Records with collections.namedtuple
Use Python's collections.namedtuple to create lightweight, immutable object-like data records, enhancing code readability and structured data handling for API responses or database rows.
from collections import namedtuple
# Define a namedtuple for representing a Point
# Arguments: typename, field_names (list of strings or space-separated string)
Point = namedtuple("Point", ["x", "y"])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
print(f"Point 1: {p1}") # Output: Point 1: Point(x=10, y=20)
print(f"Point 2: {p2}") # Output: Point 2: Point(x=30, y=40)
# Access fields by name (more readable than index)
print(f"P1 X-coordinate: {p1.x}") # Output: P1 X-coordinate: 10
print(f"P2 Y-coordinate: {p2.y}") # Output: P2 Y-coordinate: 40
# Access fields by index (like a regular tuple)
print(f"P1 Y-coordinate (by index): {p1[1]}") # Output: P1 Y-coordinate (by index): 20
# Namedtuples are immutable (like regular tuples)
try:
p1.x = 15
except AttributeError as e:
print(f"
Error trying to modify namedtuple: {e}")
# Output: Error trying to modify namedtuple: can't set attribute
# Convert to dictionary (useful for serialization)
print(f"
P1 as dict: {p1._asdict()}")
# Output: P1 as dict: {'x': 10, 'y': 20}
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides the immutability and memory efficiency of tuples while offering more readable code by allowing access to elements using descriptive names (e.g., `point.x`) instead of numerical indices. They are excellent for representing lightweight, fixed-structure data records, such as API responses, database rows, or configuration settings, similar to a C `struct` or a simple immutable class, without the overhead of defining a full class.