PYTHON

Define Structured Data with NamedTuple for Readability

Enhance code readability and maintainability by defining structured, immutable data records using `collections.namedtuple`, perfect for API results or database rows.

from collections import namedtuple

# Define a named tuple for an API response user object
User = namedtuple('User', ['id', 'username', 'email', 'status'])

# Create user instances
user1 = User(id=1, username='alice_smith', email='[email protected]', status='active')
user2 = User(id=2, username='bob_jones', email='[email protected]', status='inactive')

# Access data by field name instead of index
print(f"User 1: {user1.username} ({user1.email})")
print(f"User 2 Status: {user2.status}")

# Named tuples are immutable
# user1.status = 'banned' # This would raise an AttributeError
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This significantly improves code readability by letting you access elements using descriptive names (e.g., `user.username`) instead of integer indices (e.g., `user[1]`), while retaining the immutability and memory efficiency of regular tuples. This is especially beneficial when dealing with fixed-structure data like parsed API responses, database query results, or log entries, making your data structures more self-documenting and less prone to indexing errors.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs