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 typing import Optional, Sequence
def find_user(user_id: str, users: Sequence[dict]) -> Optional[dict]:
...
- Parameters and return values use colon and arrow syntax.
- Use
Optional[T](orT | Nonein Python 3.10+) to represent nullable returns.
Typing module essentials
| Helper | Purpose |
|---|---|
List[T], dict[str, int] | Generic collections |
Union[A, B] or `A | B` |
Literal[...] | Exact value constraints |
TypedDict, NamedTuple, Protocol | Structured types |
Callable[[ArgTypes], ReturnType] | Function signatures |
Tooling
- Run
mypy,pyright, orruff check --select=ANNto verify annotations. - Use
typing.TYPE_CHECKINGto guard import-heavy type-only dependencies.