PYTHON
Create Readable, Immutable Data Records with `collections.namedtuple`
Use `collections.namedtuple` to create lightweight, immutable object-like data records, providing more readable and self-documenting code compared to plain tuples or dictionaries for structured data.
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"X coordinate: {p1.x}, Y coordinate: {p1.y}")
# Access by index (like a regular tuple)
print(f"X by index: {p1[0]}")
# Namedtuples are immutable (this would raise an error)
# p1.x = 30
# Another example: Employee record
Employee = namedtuple('Employee', 'name age department salary')
emp1 = Employee('Alice', 30, 'HR', 60000)
emp2 = Employee(name='Bob', age=25, department='IT', salary=75000)
print(f"
Employee 1: {emp1.name} in {emp1.department}")
print(f"Employee 2: {emp2.name} earns ${emp2.salary}")
# Convert to dictionary
emp_dict = emp1._asdict()
print(f"
Employee 1 as dict: {emp_dict}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This means you can access elements by name (e.g., `point.x`) instead of by index (e.g., `point[0]`), making your code much more readable and self-documenting, especially when dealing with structured data like database records or API responses. Namedtuples are immutable, which helps prevent accidental modification, and they are more memory-efficient than dictionaries for similar purposes.