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:andname: str = "Anna". - Containers:
list[int],dict[str, float],tuple[int, str],set[str](directly from Python 3.9, earliertyping.Listetc.). - Optional and union:
str | None(from 3.10) orOptional[str]. Says: can beNone, so check before use. - More:
Callable[ [int], str ]for functions,TypedDictfor dictionaries with fixed keys,Protocolfor structural interfaces (“duck typing” with checking),Anyas an escape hatch. - mypy:
mypy file.pychecks the hints statically and reports contradictions, such as passingstrinstead ofint. 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