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
Copy
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 4Snippet 2: Immutable Nature of namedtuple
Copy
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
Copy
Snippet 4: Using _fields and _asdict
Copy
Snippet 5: Inheriting and Adding Methods to namedtuple
Copy
Snippet 6: Creating a Named Tuple with Defaults
Copy
Snippet 7: Unpacking a Named Tuple
Copy
Snippet 8: Nested namedtuple
Copy
Snippet 9: Named Tuple for Storing Database Records
Copy
Snippet 10: Using _make to Create a Named Tuple from a List
Copy
Last updated