PYTHON

Defining Immutable Data Records with `collections.namedtuple`

Create simple, immutable, and self-documenting data records using `collections.namedtuple` for clearer code and efficient data handling.

from collections import namedtuple

# Define a named tuple type for a User
User = namedtuple('User', ['id', 'username', 'email'])

# Create instances of User
user1 = User(id=1, username='johndoe', email='[email protected]')
user2 = User(2, 'janedoe', '[email protected]')

# Access data by field name or index
print(f"User 1: {user1.username}, {user1.email}")
print(f"User 2 ID: {user2[0]}")

# Named tuples are immutable
# user1.username = 'newname' # This would raise an AttributeError
How it works: `collections.namedtuple` provides an easy way to create lightweight, immutable, and self-documenting objects similar to tuples, but with named fields. This enhances code readability by allowing access to elements using descriptive names (e.g., `user.username`) instead of arbitrary indices, while retaining the memory efficiency of tuples. It's perfect for defining simple data structures where custom methods or mutability are not required.

Need help integrating this into your project?

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

Hire DigitalCodeLabs