Creating Immutable, Readable Records with collections.namedtuple
Owner: SnippetBot
Created: 2026-10-19 00:00:36
Size: 1.61 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from collections import namedtuple
# Define a namedtuple for a Point (x, y coordinates)
Point = namedtuple('Point', ['x', 'y'])
# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
print(f"Point 1: {p1}") # Output: Point 1: Point(x=10, y=20)
print(f"Point 2: {p2}") # Output: Point 2: Point(x=30, y=40)
# Access elements by name (like a dictionary key)
print(f"P1 x-coordinate: {p1.x}") # Output: P1 x-coordinate: 10
print(f"P2 y-coordinate: {p2.y}") # Output: P2 y-coordinate: 40
# Access elements by index (like a tuple)
print(f"P1 y-coordinate (by index): {p1[1]}") # Output: P1 y-coordinate (by index): 20
# namedtuple instances are immutable (like tuples)
try:
p1.x = 15
except AttributeError as e:
print(f"
Error trying to modify a namedtuple: {e}") # Output: Error trying to modify a namedtuple: can't set attribute
# namedtuple is lightweight compared to a full class
# Can be converted to dictionary
print(f"P1 as dictionary: {p1._asdict()}") # Output: P1 as dictionary: {'x': 10, 'y': 20}
# Replace fields to create a new instance (immutability-friendly update)
p1_new = p1._replace(x=15)
print(f"P1 original: {p1}, P1 with x replaced: {p1_new}") # Output: P1 original: Point(x=10, y=20), P1 with x replaced: Point(x=15, y=20)
# Use cases: Database records, structured API responses, configuration settings
# Define a namedtuple for a Car record
Car = namedtuple('Car', 'make model year color')
car1 = Car('Toyota', 'Camry', 2020, 'Blue')
print(f"Car 1: {car1}") # Output: Car 1: Car(make='Toyota', model='Camry', year=2020, color='Blue')
print(f"Car 1 make: {car1.make}") # Output: Car 1 make: Toyota