PYTHON

Create Lightweight, Immutable Data Objects with Python's collections.namedtuple

Learn to use collections.namedtuple to create simple, immutable, object-like data structures that offer attribute access and self-documenting code without full class overhead.

from collections import namedtuple

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

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

# Access elements by name or index
print(f"Point p1: x={p1.x}, y={p1.y}")
print(f"Point p2: x={p2[0]}, y={p2[1]}")

# Namedtuples are immutable
try:
    p1.x = 5 # This will raise an AttributeError
except AttributeError as e:
    print(f"Attempting to modify p1.x failed: {e}")

# Namedtuples support tuple operations
print(f"Point p1 as tuple: {p1}")
x_coord, y_coord = p1
print(f"Unpacked coords: {x_coord}, {y_coord}")

# Convert to dictionary
print(f"Point p2 as dictionary: {p2._asdict()}")
How it works: collections.namedtuple allows you to create tuple subclasses with named fields. This provides a simple way to define immutable data types that behave like objects, with attributes accessible by name (e.g., `point.x`) in addition to index-based access (e.g., `point[0]`). They are more memory-efficient than custom classes for simple data records, improve code readability by providing meaningful names for data elements, and are hashable, making them suitable for use as dictionary keys or elements in sets.

Need help integrating this into your project?

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

Hire DigitalCodeLabs