PYTHON

Create Lightweight, Immutable Objects with collections.namedtuple

Master the use of collections.namedtuple to define simple, self-documenting, and immutable data structures in Python, enhancing code readability.

from collections import namedtuple

# Define a namedtuple for representing 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}, Type: {type(p1)}")
print(f"Accessing x from p1: {p1.x}")
print(f"Accessing y from p2: {p2.y}")

# Namedtuples are immutable
try:
    p1.x = 15
except AttributeError as e:
    print(f"Cannot modify namedtuple: {e}")

# Access by index (like a regular tuple)
print(f"p1[0]: {p1[0]}")

# Convert to a dictionary
point_dict = p1._asdict()
print(f"Point as dict: {point_dict}")

# Create from iterable
coords = [50, 60]
p3 = Point._make(coords)
print(f"Point from iterable: {p3}")
How it works: A `collections.namedtuple` allows you to create tuple subclasses with named fields. This means you can access values by name (e.g., `point.x`) instead of just by index (e.g., `point[0]`), significantly improving code readability and maintainability, especially for records with multiple fields. Namedtuples are immutable, just like regular tuples, ensuring data integrity. They are lightweight alternatives to defining a full class for simple data structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs