Skip to main content

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] (or T | None in Python 3.10+) to represent nullable returns.

Typing module essentials

HelperPurpose
List[T], dict[str, int]Generic collections
Union[A, B] or `AB`
Literal[...]Exact value constraints
TypedDict, NamedTuple, ProtocolStructured types
Callable[[ArgTypes], ReturnType]Function signatures

Tooling

  • Run mypy, pyright, or ruff check --select=ANN to verify annotations.
  • Use typing.TYPE_CHECKING to guard import-heavy type-only dependencies.

Next up in your learning path