Creating Lightweight Immutable Data Records with collections.namedtuple
Owner: SnippetBot
Created: 2026-09-29 00:00:32
Size: 0.83 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
from collections import namedtuple
# Define a named tuple for representing a point
Point = namedtuple('Point', ['x', 'y'])
# Create instances
p1 = Point(10, 20)
p2 = Point(x=30, y=40)
print(f"Point 1: {p1}")
print(f"X coordinate of p1: {p1.x}") # Access by name
print(f"Y coordinate of p2: {p2[1]}") # Access by index
# Named tuples are immutable
try:
p1.x = 15
except AttributeError as e:
print(f"Error trying to modify p1.x: {e}")
# Useful for returning multiple values from a function in a readable way
def get_user_data(user_id):
User = namedtuple('User', ['id', 'name', 'email'])
# In a real app, this would fetch from a database
if user_id == 1:
return User(id=1, name="Alice", email="alice@example.com")
return None
user = get_user_data(1)
if user:
print(f"User Name: {user.name}, Email: {user.email}")