PYTHON

Create Lightweight, Immutable Data Records with Python `collections.namedtuple`

Utilize Python's `collections.namedtuple` to define simple, self-documenting data structures, enhancing code readability and ensuring data immutability for structured information like API responses or user profiles.

from collections import namedtuple

# Define a namedtuple for a user profile
UserProfile = namedtuple('UserProfile', ['id', 'username', 'email'])

# Create instances of UserProfile
user1 = UserProfile(id=1, username='johndoe', email='[email protected]')
user2 = UserProfile(2, 'janedoe', '[email protected]') # Positional arguments also work

# Access fields by name (like an object)
print(f"User 1: {user1.username}, {user1.email}")
# Output: User 1: johndoe, [email protected]

# Access fields by index (like a tuple)
print(f"User 2 ID: {user2[0]}")
# Output: User 2 ID: 2

# Namedtuples are immutable (attempting to change will raise AttributeError)
# user1.username = 'new_john' # This would raise an AttributeError
How it works: A `namedtuple` from the `collections` module allows you to create tuple subclasses with named fields. This provides a way to define simple, immutable data structures similar to C structs or database rows, offering improved readability over plain tuples by allowing access to elements by name (e.g., `user.username`) while retaining the memory efficiency of tuples. It's excellent for representing records where the structure is fixed and read-only.

Need help integrating this into your project?

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

Hire DigitalCodeLabs