PYTHON
Create Immutable Data Objects with `namedtuple`
Learn to define lightweight, immutable object-like data structures using Python's `collections.namedtuple` for cleaner, self-documenting code.
from collections import namedtuple
# Define a namedtuple for a User
User = namedtuple('User', ['id', 'username', 'email'])
# Create user instances
user1 = User(id=1, username='john_doe', email='[email protected]')
user2 = User(id=2, username='jane_smith', email='[email protected]')
print(user1.username)
print(user2.email)
# Trying to modify a namedtuple will raise an AttributeError
# user1.username = 'new_username' # Uncommenting this will cause an error
# Convert to dictionary (if needed)
user_dict = user1._asdict()
print(user_dict)
# Output:
# john_doe
# [email protected]
# {'id': 1, 'username': 'john_doe', 'email': '[email protected]'}
How it works: `collections.namedtuple` provides a way to create tuple subclasses with named fields. This allows you to access elements by name (e.g., `user.username`) instead of index, making code more readable and self-documenting, especially when dealing with fixed-structure data like database records or API responses. They are immutable by nature, which helps ensure data integrity.