PYTHON
Create Immutable, Readable Data Records with `namedtuple`
Use Python's `collections.namedtuple` to define lightweight, immutable object types with named fields, enhancing code clarity and preventing accidental modifications.
from collections import namedtuple
# Define a namedtuple for a User record
User = namedtuple("User", ["id", "username", "email"])
# Create instances of the User namedtuple
user1 = User(id=1, username="alice", email="[email protected]")
user2 = User(id=2, username="bob", email="[email protected]")
# Access fields by name or index
print(f"User 1 username: {user1.username}")
print(f"User 2 email: {user2[2]}") # Access by index is also possible
# namedtuples are immutable
try:
user1.id = 100
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}")
# Convert to dictionary if needed
user_dict = user1._asdict()
print(f"User 1 as dict: {user_dict}")
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 the readability of object attribute access (e.g., `user.username`). It's ideal for defining simple, fixed-schema data records, like API response objects or database rows, where you want to ensure data integrity and make your code more self-documenting without the overhead of a full class.