Type Annotations
Understanding Type Annotations
Type annotations in Python provide a way to indicate the expected types of variables, function parameters, and return values. Introduced in Python 3.5, they offer improved code readability and help catch type-related errors early.
Basic Annotation Syntax
## Variable annotations
name: str = "LabEx"
age: int = 25
## Function parameter and return type annotations
def greet(name: str) -> str:
return f"Hello, {name}!"
Annotation Types
| Annotation Type |
Example |
Description |
| Simple Types |
x: int |
Basic type specification |
| Complex Types |
list[int] |
Container with specific element type |
| Optional Types |
Optional[str] |
Value can be of specified type or None |
| Union Types |
Union[int, str] |
Multiple possible types |
Advanced Annotation Techniques
from typing import List, Dict, Tuple, Optional
def process_data(
items: List[int],
mapping: Dict[str, float],
coordinates: Tuple[int, int]
) -> Optional[float]:
## Function implementation
pass
graph TD
A[Type Annotation] --> B[Static Type Checkers]
B --> C[mypy]
B --> D[PyCharm]
B --> E[Pyright]
Practical Benefits
- Improved code documentation
- Better IDE support
- Early error detection
- Enhanced code readability
Runtime Type Checking
def validate_type(value: int) -> int:
if not isinstance(value, int):
raise TypeError(f"Expected int, got {type(value)}")
return value
Common Annotation Patterns
from typing import Callable, Any
## Function as a parameter
def apply_function(func: Callable[[int], str], value: int) -> str:
return func(value)
## Generic types
def first_element[T](items: List[T]) -> Optional[T]:
return items[0] if items else None
Best Practices
- Use type annotations consistently
- Keep annotations clear and simple
- Leverage type checking tools
- Don't over-annotate trivial code
Type annotations in Python provide a powerful way to add type information to your code, improving its quality and maintainability.