Practical Annotation Examples
Real-World Type Annotation Scenarios
Data Processing Functions
from typing import List, Dict, Optional
def filter_valid_users(users: List[Dict[str, str]]) -> List[Dict[str, str]]:
return [user for user in users if user.get('email')]
def calculate_average(numbers: List[float]) -> Optional[float]:
return sum(numbers) / len(numbers) if numbers else None
API and Network Interaction
from typing import Union, Dict, Any
def fetch_api_data(endpoint: str) -> Union[Dict[str, Any], None]:
try:
## Simulated API request
return {"status": "success", "data": [1, 2, 3]}
except Exception:
return None
Error Handling and Type Annotations
from typing import Tuple, Union
def divide_numbers(a: float, b: float) -> Union[float, str]:
try:
return a / b
except ZeroDivisionError:
return "Division by zero error"
Annotation Strategy Comparison
Scenario |
Return Type |
Annotation Strategy |
Complexity |
Simple Calculation |
Numeric |
Direct type |
Low |
Data Filtering |
List |
Generic type |
Medium |
Error Handling |
Union |
Multiple possible returns |
High |
Type Annotation Flow
graph TD
A[Function Input] --> B{Process Data}
B --> C{Validate Return}
C --> |Valid Type| D[Return Annotated Result]
C --> |Type Mismatch| E[Raise Type Error]
Advanced Annotation Techniques
from typing import Callable, TypeVar
T = TypeVar('T')
R = TypeVar('R')
def apply_transform(
data: List[T],
transformer: Callable[[T], R]
) -> List[R]:
return [transformer(item) for item in data]
Decorator Type Annotations
from typing import Callable, Any
def log_return(func: Callable[..., Any]) -> Callable[..., Any]:
def wrapper(*args: Any, **kwargs: Any) -> Any:
result = func(*args, **kwargs)
print(f"Function returned: {result}")
return result
return wrapper
@log_return
def example_function(x: int) -> str:
return str(x * 2)
Best Practices
- Use precise type annotations
- Handle potential edge cases
- Leverage typing module capabilities
- Consider runtime type validation
LabEx Insight
Explore complex type annotation scenarios in LabEx Python environments to enhance your type hinting skills.
Common Challenges
- Balancing type specificity and flexibility
- Managing complex return type scenarios
- Maintaining type hint readability
- Integrating with existing codebases