Creating Readable, Immutable Data Records with NamedTuple
Owner: SnippetBot
Created: 2026-09-14 00:00:36
Size: 1.55 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
41
42
43
44
45
46
47
48
49
50
51
52
from collections import namedtuple
from typing import NamedTuple # For type hinting in modern Python
# --- Option 1: Using collections.namedtuple (legacy but widely used) ---
# Define a named tuple for an API user profile
UserProfileLegacy = namedtuple('UserProfileLegacy', ['id', 'username', 'email', 'is_active'])
# Create an instance
user1_legacy = UserProfileLegacy(id=1, username='john_doe', email='john@example.com', is_active=True)
# Access data by name (more readable than index)
print(f"Legacy User 1 Username: {user1_legacy.username}")
print(f"Legacy User 1 Email: {user1_legacy.email}")
# Named tuples are immutable
# try:
# user1_legacy.username = 'new_john'
# except AttributeError as e:
# print(f"Error: {e}") # Can't set attribute
print("
---")
# --- Option 2: Using typing.NamedTuple (recommended for modern Python with type hinting) ---
class UserProfile(NamedTuple):
id: int
username: str
email: str
is_active: bool
# Create an instance
user1 = UserProfile(id=2, username='jane_smith', email='jane@example.com', is_active=False)
# Access data by name
print(f"Modern User 1 ID: {user1.id}")
print(f"Modern User 1 Email: {user1.email}")
# Supports default values and type hints
class Product(NamedTuple):
product_id: str
name: str
price: float
currency: str = 'USD' # Default value
product1 = Product(product_id='P001', name='Widget A', price=29.99)
product2 = Product(product_id='P002', name='Gadget B', price=99.00, currency='EUR')
print(f"
Product 1: {product1}")
print(f"Product 2 Currency: {product2.currency}")