Python doesn't make you say what type a variable holds, which keeps small scripts quick to write. In big programs, though, "what does this function take, and what does it give back?" becomes the main question. Type hints answer it in the code itself: name: str after a parameter and -> int after the brackets.
def repeat(text: str, times: int = 2) -> str:
return text * times
print(repeat("ab"))
print(repeat.__annotations__)
Python itself doesn't enforce hints when the program runs: repeat(3, 2) would still run. They're read by tools. A type checker such as mypy or pyright reads the whole program and reports mismatches before you run it, and editors use hints for autocomplete and warnings as you type.
def repeat(text: str, times: int = 2) -> str:
return text * times
print(repeat(3, 2))
Prints
6
No error at run time, but a type checker would flag that call. The common forms: built-in types (int, str, bool), containers with what's inside them (list[int], dict[str, float], tuple[int, str], set[str]), X | None for a value that might be missing, X | Y for either, and Callable[[int], str] for a function. Variables can be annotated too: scores: dict[str, int] = {}.
from collections.abc import Callable, Iterable
def find(names: list[str], target: str) -> int | None:
for i, n in enumerate(names):
if n == target:
return i
return None
def apply_all(fn: Callable[[int], int], xs: Iterable[int]) -> list[int]:
return [fn(x) for x in xs]
print(find(["a", "b"], "b"), find(["a"], "z"))
print(apply_all(lambda x: x + 1, range(3)))
Prints
1 None
[1, 2, 3]
Hint parameters with the most general type that works (Iterable[int] accepts lists, tuples, sets and generators) and return the most specific one. When a value might be None, the type checker makes you handle that case, which catches a whole class of crashes.
Duck typing has a typed form too. A Protocol describes the methods an object must have, and any class with those methods matches, without inheriting from anything. TypedDict describes the keys of a dict, handy for JSON data, and TypeVar or the newer def first[T](xs: list[T]) -> T syntax writes functions that keep the type of what they're given (generics).
from typing import Protocol
class Speaker(Protocol):
def speak(self) -> str: ...
class Duck:
def speak(self) -> str:
return "Quack"
def chorus(things: list[Speaker]) -> str:
return " ".join(t.speak() for t in things)
print(chorus([Duck(), Duck()]))
Prints
Quack Quack
(The ... there is Python's placeholder for "no body here".) Add hints to anything other people call: function signatures, class attributes, a library's public names. Local variables rarely need them, since the checker can usually work them out.
Practice
What happens when this runs (without a type checker)?
def double(n: int) -> int:
return n * 2
print(double("ha"))
More info
Quick reference
def f(x: int) -> str:
Parameter and return type hints.
list[int] dict[str, float] tuple[int, str]
Containers and what's inside them.
X | None / X | Y
Might be missing / either type.
Callable[[int], str] / Iterable[int]
A function / anything you can loop over.
Protocol
Describes required methods; any matching class fits.
mypy / pyright
Type checkers: report mismatches without running the code.