Applying Typed Data Structures in Practice
Now that you have a solid understanding of how to define typed data structures in Python, let's explore some practical applications and use cases.
- Using typed data structures to validate input data
- Transforming data between different structured formats
from typing import TypedDict, List, Dict
class WeatherData(TypedDict):
city: str
temperature: float
humidity: float
def process_weather_data(data: List[Dict[str, Any]]) -> List[WeatherData]:
result: List[WeatherData] = []
for item in data:
result.append({
"city": item["location"],
"temperature": item["temp"],
"humidity": item["humidity"]
})
return result
API and Database Modeling
- Defining typed data structures for API request/response payloads
- Mapping database models to typed data structures
from typing import TypedDict, List, Optional
class UserResponse(TypedDict):
id: int
name: str
email: Optional[str]
created_at: str
def get_users() -> List[UserResponse]:
## Fetch users from a database or API
## and return a list of UserResponse objects
pass
Type-Driven Development
- Using typed data structures to drive the design and implementation of your code
- Leveraging type annotations to improve code readability and maintainability
from typing import Tuple, Literal
def calculate_area(shape: Literal["rectangle", "circle"], *args: float) -> float:
if shape == "rectangle":
width, height = args
return width * height
elif shape == "circle":
radius, = args
return 3.14 * radius ** 2
else:
raise ValueError(f"Invalid shape: {shape}")
area: float = calculate_area("circle", 5.0)
By applying typed data structures in these practical scenarios, you can improve the overall quality and reliability of your Python applications, making them more robust, maintainable, and easier to work with.