PYTHON
Create Lightweight, Immutable Data Objects with namedtuple
Learn to define simple, immutable data structures with named fields using `collections.namedtuple`, providing a readable alternative to tuples and classes.
from collections import namedtuple
# Define a namedtuple type for representing a Point
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
print(f"Point 1: {p1}")
print(f"Point 2: {p2}")
# Access fields by name or index
print(f"p1.x: {p1.x}, p1.y: {p1.y}")
print(f"p2[0]: {p2[0]}, p2[1]: {p2[1]}")
# Namedtuples are immutable (like regular tuples)
try:
p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
print(f"Attempting to modify p1.x failed: {e}")
# Namedtuples provide a helpful __repr__
print(f"Representation: {repr(p1)}")
# Can also be used for more complex data
Student = namedtuple('Student', 'name age major gpa')
s1 = Student('Alice', 20, 'CS', 3.8)
s2 = Student('Bob', 21, 'Math', 3.5)
print(f"Student 1: {s1.name}, Major: {s1.major}")
How it works: This snippet demonstrates the use of `collections.namedtuple` to create lightweight, immutable data objects. A `namedtuple` is a factory function for creating tuple subclasses with named fields. This allows you to access values by name (e.g., `point.x`) instead of just by index (e.g., `point[0]`), significantly improving code readability and self-documentation, while retaining the memory efficiency and immutability of regular tuples. It's an excellent choice for representing simple record-like structures where a full-fledged class might be overkill.