PYTHON
Type-Hinting Complex Dictionary Structures with `TypedDict`
Improve code readability and maintainability by explicitly type-hinting complex dictionary structures, like API responses, using Python's `TypedDict`.
from typing import List, TypedDict, Optional
class Address(TypedDict):
street: str
city: str
zip_code: str
class UserProfile(TypedDict):
id: int
name: str
email: str
address: Address
phone: Optional[str]
# Example function returning a structured API response
def fetch_user_profile(user_id: int) -> UserProfile:
# In a real app, this would fetch data from a database or external API
if user_id == 1:
return {
"id": 1,
"name": "Alice Wonderland",
"email": "[email protected]",
"address": {
"street": "123 Rabbit Hole",
"city": "Wonderland",
"zip_code": "W0N D3R"
},
"phone": "555-1234"
}
elif user_id == 2:
return {
"id": 2,
"name": "Bob The Builder",
"email": "[email protected]",
"address": {
"street": "456 Tool Road",
"city": "Constructionville",
"zip_code": "C0N STR"
}
# 'phone' is optional, so it can be omitted
}
else:
raise ValueError("User not found")
# How to use the type-hinted dictionary
profile: UserProfile = fetch_user_profile(1)
print(f"User ID: {profile['id']}, Name: {profile['name']}")
print(f"Address: {profile['address']['street']}, {profile['address']['city']}")
profile_no_phone = fetch_user_profile(2)
if profile_no_phone.get('phone'):
print(f"Phone: {profile_no_phone['phone']}")
else:
print(f"{profile_no_phone['name']} has no phone listed.")
# Mypy or other static analyzers would catch issues like this:
# invalid_profile: UserProfile = {"id": 3, "name": "Charlie", "email": "[email protected]"} # Missing address
How it works: `TypedDict` allows you to declare a dictionary type where keys are strings and values have specific types. This is incredibly useful for web developers when working with JSON data, configuration files, or API responses, where the structure is dictionary-like but needs more robust type checking than a generic `Dict[str, Any]`. It enhances code clarity and helps static type checkers like Mypy catch potential errors before runtime, making code more maintainable.