28.Type Hints & mypy
Type hints and static type checking are powerful features in Python that help developers write more robust and maintainable code.
Type Hints
Type hints allow developers to annotate variables, function parameters, and return types with expected data types. They do not affect runtime behavior but serve as documentation and enable tools like mypy to perform static type checking.
Syntax and Examples
Basic Type Hinting:
def greet(name: str) -> str:
return ‘Hello ‘ + name
Type Hinting with Lists and Dictionaries:
from typing import List, Dict
def process_scores(scores: List[int]) -> Dict[str, float]:
return {‘average’: sum(scores)/len(scores)}
Optional and Union Types:
from typing import Optional, Union
def get_length(s: Optional[str]) -> Union[int, None]:
if s:
return len(s)
return None
Benefits of Type Hints
- Improved code readability and documentation
- Early detection of bugs via static analysis
- Better IDE support with autocompletion and type checking
- Facilitates refactoring and maintenance
Using mypy for Static Type Checking
mypy is a static type checker for Python. It reads type hints and checks for type consistency without executing the code.
To use mypy:
- Install mypy using pip: pip install mypy
- Add type hints to your Python code
- Run mypy on your script: mypy script.py
- Review and fix any type errors reported
Common Use Cases
- Large codebases where type consistency is critical
- Collaborative projects to ensure clear contracts between functions
- APIs and libraries to provide better documentation and usage clarity
- Educational settings to teach data types and function signatures
Best Practices
- Use type hints consistently across your codebase
- Prefer built-in types over overly complex annotations
- Use Optional and Union types when necessary
- Run mypy regularly to catch type issues early
- Avoid excessive type hinting that may reduce readability
Limitations
- Type hints do not enforce types at runtime
- Complex type annotations can reduce readability
- Requires additional tooling like mypy for enforcement
- May not catch all logical errors