EMZETT.
Login

Python: type hints and mypy

In short: Type hints (type annotations) write the expected types of parameters, return values and variables into Python code. Python does not enforce them, but tools such as mypy and editors check them.

In more detail: Python stays dynamically typed. The hints serve people and tools: better autocompletion, early error messages, more readable interfaces.

In Depth

  • Basic form: def price(net: float, tax: float = 0.19) -> float: and name: str = "Anna".
  • Containers: list[int], dict[str, float], tuple[int, str], set[str] (directly from Python 3.9, earlier typing.List etc.).
  • Optional and union: str | None (from 3.10) or Optional[str]. Says: can be None, so check before use.
  • More: Callable[ [int], str ] for functions, TypedDict for dictionaries with fixed keys, Protocol for structural interfaces (“duck typing” with checking), Any as an escape hatch.
  • mypy: mypy file.py checks the hints statically and reports contradictions, such as passing str instead of int. Alternatives: pyright (in Pylance), pytype.
  • Gradual: You can annotate individual files or functions. Unannotated code is treated leniently.
  • Runtime: Libraries such as Pydantic or FastAPI read the hints and validate inputs.
  • Limit: Hints guarantee nothing at runtime.

See also: type systems and type inference, linters, formatters and type checkers