How do type hints and static type checking work in Python?
· Category: Python Programming
Short answer
Type hints are annotations that describe the expected types of variables, function parameters, and return values. They are ignored at runtime but can be checked statically with tools like mypy.
Steps
- Import types from
typingor use built-in generics (Python 3.9+). - Annotate functions and variables.
- Run
mypyto check for type errors.
from typing import List, Dict, Optional
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}!
") * times
def process(items: List[int]) -> Dict[str, int]:
return {f"item_{i}": v for i, v in enumerate(items)}
def find(user_id: int) -> Optional[str]:
if user_id == 1:
return "Alice"
return None
Tips
- Start by annotating function signatures; variable annotations can come later.
- Use
typing.Protocolorabc.ABCfor structural subtyping. mypy --strictenables the most rigorous checks.- Python 3.10+ supports
X | Yunion syntax; 3.9+ supportslist[int]withouttyping.List.
Common issues
- Type hints do not prevent runtime type errors; they are documentation and static-checking aids.
- Circular imports can occur when type annotations reference classes defined later; use string forward references or
from __future__ import annotations. - Overly complex type signatures reduce readability; alias complex types with
TypeAlias.