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}")