Python Type Hints
Satellite · Functions
Type Hints
PEP 484 introduced optional typing to Python. Learn the basics so your functions communicate intent clearly and static analyzers can help.
Functions
from collections.abc import Sequence
def find_user(user_id: str, users: Sequence[dict]) -> dict | None:
...
- Parameters and return values use colon and arrow syntax.
- Since Python 3.9, use built-in generics directly:
list[int],dict[str, int],tuple[int, ...]. - Use
T | None(Python 3.10+) to represent nullable returns;typing.Optional[T]is the legacy spelling. - For abstract container types, import from
collections.abc(Sequence,Iterable,Mapping).
Typing essentials
| Helper | Purpose |
|---|---|
list[T], dict[str, int] | Generic collections (built-ins since 3.9; typing.List is legacy) |
A | B or Union[A, B] | Multiple allowed types |
Literal[...] | Exact value constraints |
TypedDict, NamedTuple, Protocol | Structured types |
Callable[[ArgTypes], ReturnType] | Function signatures (collections.abc.Callable) |
Tooling
- Run
mypy,pyright, orruff check --select=ANNto verify annotations. - Use
typing.TYPE_CHECKINGto guard import-heavy type-only dependencies.