PYTHON

Define Lightweight Immutable Data Records with collections.namedtuple

Improve code readability and structure by creating simple, immutable data objects with named fields using Python's `collections.namedtuple`, ideal for fixed-schema data.

from collections import namedtuple

# Define a namedtuple for a Point
Point = namedtuple('Point', ['x', 'y'])

# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)

print(f"Point 1: {p1}")
print(f"X coordinate of p1: {p1.x}")
print(f"Y coordinate of p2: {p2.y}")

# Accessing like a tuple
print(f"P1 as tuple: {p1[0]}, {p1[1]}")

# Namedtuples are immutable (this would raise an AttributeError)
# p1.x = 15

# Convert to dictionary
print(f"P1 as dict: {p1._asdict()}")

# Define a namedtuple for a User Profile
UserProfile = namedtuple('UserProfile', 'id username email is_active')

user = UserProfile(id=1, username='jdoe', email='[email protected]', is_active=True)
print(f"User profile: {user.username}, {user.email}")

# Example output:
# Point 1: Point(x=10, y=20)
# X coordinate of p1: 10
# Y coordinate of p2: 40
# P1 as tuple: 10, 20
# P1 as dict: OrderedDict([('x', 10), ('y', 20)])
# User profile: jdoe, [email protected]
How it works: A `namedtuple` from the `collections` module allows you to create tuple-like objects that have fields accessible by attribute lookup as well as by index. This makes your code more readable by giving meaning to the data stored at each position, without the overhead of a full class definition. They are immutable, ensuring that the data they hold remains constant after creation, which is beneficial for representing fixed records or database rows.

Need help integrating this into your project?

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

Hire DigitalCodeLabs