mypy, and validation libraries like Pydantic — which is at the heart of FastAPI. Understanding type hints is a prerequisite for working effectively with Pydantic models and FastAPI routes.
Basic Variable Type Hints
You annotate a variable using a colon followed by the type:: str, : int, : float, and : bool parts are type hints — they document intent but do not enforce anything at runtime.
Python Doesn’t Enforce Type Hints
This is the most important thing to understand upfront:- Documentation — code becomes self-explanatory.
- IDE support — autocomplete, inline error detection, and refactoring work better.
- Validation tools — Pydantic, mypy, and others read and act on them.
Basic Types
The four types you’ll annotate most often:Container Types
For collections, you specify the type of their contents:Python 3.9+ supports lowercase built-in types (
list, dict, set, tuple) directly in annotations. Older code imports uppercase equivalents from typing (List, Dict). They are equivalent — prefer the lowercase built-in syntax in new code.Optional Values
When a value might beNone, use Optional from typing or the | union syntax (Python 3.10+):
Literal Types
When a variable must be one of a fixed set of values, useLiteral:
Function Type Hints
Type hints on function parameters and return values are especially valuable:-> str after the closing parenthesis declares the return type.