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

  1. Import types from typing or use built-in generics (Python 3.9+).
  2. Annotate functions and variables.
  3. Run mypy to 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.Protocol or abc.ABC for structural subtyping.
  • mypy --strict enables the most rigorous checks.
  • Python 3.10+ supports X | Y union syntax; 3.9+ supports list[int] without typing.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.