Using collections.namedtuple for Readable Data Records
Owner: SnippetBot
Created: 2026-08-30 00:00:21
Size: 2.02 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
from collections import namedtuple
# Define a namedtuple for a User record
# This creates a new class-like object 'User' with specified field names.
User = namedtuple('User', ['id', 'username', 'email', 'is_active'])
# Define a namedtuple for a Product record
Product = namedtuple('Product', 'id name price category') # Can also use a space-separated string
def create_user(user_id, username, email, is_active=True):
"""Creates a new User record.
"""
return User(id=user_id, username=username, email=email, is_active=is_active)
def format_product_info(product_record):
"""Formats product information from a namedtuple.
"""
return f"Product: {product_record.name} (ID: {product_record.id}), Price: ${product_record.price:.2f}, Category: {product_record.category}"
# Example Usage - User:
user1 = create_user(101, 'john_doe', 'john.doe@example.com')
user2 = create_user(102, 'jane_smith', 'jane.smith@example.com', is_active=False)
print(f"User 1 ID: {user1.id}, Username: {user1.username}, Active: {user1.is_active}")
print(f"User 2 Email: {user2.email}")
# Namedtuples are immutable, like regular tuples
try:
user1.username = 'new_john'
except AttributeError as e:
print(f"Error trying to modify namedtuple: {e}") # Expected error
# Namedtuples support unpacking
user_id, uname, uemail, uactive = user1
print(f"Unpacked User 1 ID: {user_id}, Name: {uname}")
# Example Usage - Product:
product1 = Product(id=201, name='Wireless Mouse', price=25.99, category='Electronics')
product2 = Product(202, 'Coffee Maker', 89.50, 'Home Appliances') # Positional arguments also work
print(format_product_info(product1))
print(f"Product 2 Category: {product2.category}")
# Namedtuples are more readable than regular tuples for structured data
db_row = ('001', 'Widget X', 19.99)
# print(f"Item: {db_row[1]}, Cost: {db_row[2]}") # Less readable
ProductRow = namedtuple('ProductRow', ['sku', 'name', 'cost'])
product_record = ProductRow('001', 'Widget X', 19.99)
print(f"Item: {product_record.name}, Cost: {product_record.cost}") # Much clearer