152. collections.namedtuple for Immutable Objects

Here are 10 Python snippets demonstrating the use of collections.namedtuple for creating lightweight, immutable objects with named fields. Each snippet is separated by a delimiter.


Snippet 1: Creating a Point with namedtuple

from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p)          # Output: Point(x=3, y=4)
print(p.x, p.y)   # Output: 3 4

Snippet 2: Immutable Nature of namedtuple

from collections import namedtuple

Car = namedtuple('Car', ['make', 'model', 'year'])
car = Car('Toyota', 'Corolla', 2020)

# Access fields
print(car.make)  # Output: Toyota

# Attempting to modify will raise an error
try:
    car.year = 2022
except AttributeError as e:
    print(e)  # Output: "can't set attribute"

Snippet 3: Adding Defaults Using _replace


Snippet 4: Using _fields and _asdict


Snippet 5: Inheriting and Adding Methods to namedtuple


Snippet 6: Creating a Named Tuple with Defaults


Snippet 7: Unpacking a Named Tuple


Snippet 8: Nested namedtuple


Snippet 9: Named Tuple for Storing Database Records


Snippet 10: Using _make to Create a Named Tuple from a List


Last updated