PYTHON
Creating Immutable Data Objects with collections.namedtuple
Learn to create simple, immutable objects with named fields using Python's `collections.namedtuple`. Ideal for structured data without the boilerplate of full classes.
from collections import namedtuple
# Define a namedtuple for representing a Point
Point = namedtuple('Point', ['x', 'y'])
# Create instances
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 tuples)
try:
p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}")
# Namedtuples can be converted to dictionaries
print(f"Point 1 as dict: {p1._asdict()}")
# Access field names
print(f"Field names: {Point._fields}")
# Example with more complex data
Book = namedtuple('Book', 'title author year')
book1 = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979)
print(f"Book 1: {book1.title} by {book1.author}, published in {book1.year}")
How it works: `collections.namedtuple` is a factory function for creating tuple subclasses with named fields. It provides an easy way to create lightweight, immutable objects for storing structured data, similar to a C `struct` or database row. Instances are as memory-efficient as regular tuples but allow accessing fields by name (e.g., `point.x`) instead of just by index (e.g., `point[0]`), making the code more readable and self-documenting. They are immutable, ensuring data integrity once created.