PYTHON
Create Lightweight, Readable Data Structures with Namedtuple
Discover how collections.namedtuple provides an easy way to define immutable object-like data structures with named fields, enhancing code readability.
from collections import namedtuple
# Define a namedtuple for a User
User = namedtuple('User', ['id', 'username', 'email'])
# Create instances of User
user1 = User(id=1, username='alice', email='[email protected]')
user2 = User(id=2, username='bob', email='[email protected]')
# Access fields by name
# print(f"User 1 username: {user1.username}") # alice
# print(f"User 2 email: {user2.email}") # [email protected]
# Access fields by index (like a tuple)
# print(f"User 1 ID (by index): {user1[0]}") # 1
# Namedtuples are immutable
try:
user1.username = 'alicia'
except AttributeError as e:
# print(f"Error trying to modify namedtuple: {e}")
pass
# Can be easily converted to dictionary
user1_dict = user1._asdict()
# print(f"User 1 as dict: {user1_dict}") # {'id': 1, 'username': 'alice', 'email': '[email protected]'}
How it works: collections.namedtuple allows you to create tuple subclasses with named fields. This provides a clear, self-documenting way to store structured, immutable data, making your code more readable and less error-prone than using plain tuples or dictionaries for simple records. Fields can be accessed by name (e.g., user.username) or by index.