Skip to main content
Type hints are one of Python’s most practical features for writing clear, maintainable code. They tell you — and your tools — what type of data a variable, parameter, or function should carry. While Python’s runtime ignores them completely (they’re never enforced by the interpreter), they are actively read and used by your IDE, static analysis tools like 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:
The : 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:
Type hints are annotations, not constraints. The Python interpreter runs this code without complaint. They exist for three purposes:
  1. Documentation — code becomes self-explanatory.
  2. IDE support — autocomplete, inline error detection, and refactoring work better.
  3. 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 be None, 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, use Literal:

Function Type Hints

Type hints on function parameters and return values are especially valuable:
The -> str after the closing parenthesis declares the return type.

Common Patterns

Type Hints Don’t Validate — Pydantic Does

Remember: Python’s runtime ignores type hints entirely:
This is exactly where Pydantic comes in. Pydantic reads your type hints at class-definition time and generates real validators that run when objects are created:
FastAPI uses Pydantic models for all request and response bodies, so your type hints automatically become validation rules, serialisation schemas, and OpenAPI documentation — all at once.