PYTHON

Define Lightweight Immutable Data Objects

Create simple, immutable data structures with named fields using `collections.namedtuple`, offering readability and immutability without full class overhead.

from collections import namedtuple

# Define a namedtuple for a point
Point = namedtuple('Point', ['x', 'y'])
p1 = Point(10, 20)
print(f"Point: {p1.x}, {p1.y}")
# Output: Point: 10, 20

# Access by index or attribute name
print(f"X-coordinate: {p1[0]}")
print(f"Y-coordinate: {p1.y}")

# Namedtuples are immutable
try:
    p1.x = 30
except AttributeError as e:
    print(f"Error: {e}")
# Output: Error: can't set attribute

# Use in a list of records
User = namedtuple('User', 'id name email')
users = [
    User(1, 'Alice', '[email protected]'),
    User(2, 'Bob', '[email protected]')
]
print(f"User 1 email: {users[0].email}")
# Output: User 1 email: [email protected]
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields, enabling access to elements by name (e.g., `point.x`) rather than just by index. This significantly enhances code readability and self-documentation. Namedtuples are inherently immutable, making them excellent for representing fixed data records such as coordinates, database rows, or API responses where data integrity is paramount, while being more lightweight than full classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs