PYTHON

Creating Immutable Objects with collections.namedtuple

Learn how to define simple, lightweight, immutable object-like data structures in Python using collections.namedtuple for enhanced readability and safety in your web applications.

from collections import namedtuple

# Define a namedtuple type 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}")        # Point(x=10, y=20)
print(f"Point 2: {p2}")        # Point(x=30, y=40)
print(f"X coordinate of p1: {p1.x}") # Access by name
print(f"Y coordinate of p2: {p2[1]}") # Access by index (like a tuple)

# Namedtuples are immutable (like tuples)
try:
    p1.x = 15
except AttributeError as e:
    print(f"Error trying to modify: {e}") # AttributeError: can't set attribute

# Convert to dictionary (useful for serialization)
print(f"p1 as dict: {p1._asdict()}") # OrderedDict([('x', 10), ('y', 20)])

# Using namedtuple for more complex data
Color = namedtuple('Color', 'red green blue alpha')
c1 = Color(255, 0, 0, 1.0)
print(f"Color: {c1.red}, {c1.green}, {c1.blue}, {c1.alpha}")
How it works: `collections.namedtuple` provides a way to create simple, lightweight class-like objects that are immutable, similar to tuples but with readable field names instead of integer indices. This improves code readability and reduces errors by preventing accidental modification of object attributes. Namedtuples are excellent for defining records like database results or API response structures where immutability and clear attribute access are desired, consuming less memory than full custom classes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs