PYTHON
Create Immutable Data Records with Namedtuple
Use `collections.namedtuple` in Python to define lightweight, immutable record types, enhancing code readability and data access without the boilerplate of full class definitions.
from collections import namedtuple
# Define a namedtuple for representing a User
# Arguments: type_name, field_names (as a space-separated string or list of strings)
User = namedtuple('User', ['id', 'username', 'email'])
# Create instances of the User namedtuple
user1 = User(id=1, username='john_doe', email='[email protected]')
user2 = User(id=2, username='jane_smith', email='[email protected]')
# Access fields using dot notation (like object attributes)
# print(f"User 1: {user1.username} ({user1.email})")
# Expected output: User 1: john_doe ([email protected])
# Access fields using index (like a regular tuple)
# print(f"User 2 ID: {user2[0]}")
# Expected output: User 2 ID: 2
# Namedtuples are immutable (cannot change values after creation)
try:
user1.username = 'new_john'
except AttributeError as e:
# print(f"Error attempting to modify: {e}")
pass # This will raise an AttributeError
# Convert to dictionary
# print(user1._asdict())
# Expected output: OrderedDict([('id', 1), ('username', 'john_doe'), ('email', '[email protected]')])
# Iterate through fields
# for field in user1:
# print(field)
# Expected output:
# 1
# john_doe
# [email protected]
How it works: The `collections.namedtuple` factory function allows you to create tuple subclasses with named fields. This means you can access values using dot notation (e.g., `user.username`) instead of integer indices, significantly improving code readability and making your data structures self-documenting. Namedtuples are immutable, providing data integrity, and are lighter than full-blown classes. They are ideal for parsing structured data (like API responses or database records) where you want to define a clear, fixed structure without the overhead of custom class definitions.