Dev tools
Python Type Hints: A Practical Guide With Examples
Python type hints explained with examples: syntax for functions, lists, dicts, Optional, Callable and Protocol, plus mypy, Pyright and a cheat sheet.
Python type hints are optional annotations that say what type a variable, function argument or return value should have, such as def greet(name: str) -> str:. Python itself ignores them at runtime; tools like mypy, Pyright and your editor read them to catch bugs before the code runs, power autocomplete and document what a function expects. Start by annotating function signatures, run a type checker in CI, and add detail where it pays off.
This guide covers what Python type hints are, the syntax for every common case (with default values, containers, None, callables, classes and generics), how the type checkers differ, the version history, a worked example of adding hints to real code, and a Python type hints cheat sheet you can keep open while you work.
What Are Python Type Hints?
What are Python type hints, in one line? They are labels that describe the types your code expects, written with a colon after a name and an arrow before a return type. They were introduced by PEP 484 in Python 3.5 (2015), with variable annotations added by PEP 526 in Python 3.6.
def area(width: float, height: float) -> float:
return width * height
count: int = 0
names: list[str] = ["Ada", "Grace"]Python is still a dynamically typed language. PEP 484 states plainly that the authors have "no desire to ever make type hints mandatory, even by convention." Hints are metadata: Python stores them, and other tools use them. That design is called gradual typing: you can annotate one function today and leave the rest of the codebase alone, and anything without a hint is treated as Any, a type that is compatible with everything.
Why bother, if nothing enforces them? Three practical reasons:
- Bugs found earlier. A type checker flags
len(5), a missingNonecheck or a wrong argument order before the code ever runs. On a large codebase, those are the bugs that otherwise reach production. - Better editor support. Autocomplete, go-to-definition and safe renames all work far better when the editor knows that
useris aUserand not "anything". - Documentation that can't go stale. A signature like
def fetch(url: str, timeout: float = 10.0) -> bytestells a reader more than most docstrings, and the checker complains if it stops being true.
They also matter more than they used to. Libraries such as Pydantic, FastAPI, SQLModel, Typer and dataclasses read hints at runtime to validate data, generate API schemas or build command-line interfaces. And AI coding assistants produce noticeably better completions in typed code, because the hints narrow what a correct answer looks like.
Does Python Enforce Type Hints?
No. Does Python enforce type hints at runtime? It does not: the interpreter runs this code without complaint.
def double(x: int) -> int:
return x * 2
print(double("ha")) # prints "haha", no errorThe mismatch is only caught when you run a static type checker, which reads the source without executing it:
pip install mypy
mypy app.py # error: Argument 1 to "double" has incompatible type "str"; expected "int"There is no measurable runtime cost to most hints either. Since Python 3.14, annotations are not even evaluated when a function is defined: PEP 649 and PEP 749 made evaluation lazy, so hints are stored and only computed if something asks for them (through the new annotationlib module or typing.get_type_hints). A side effect is that forward references no longer need quotes.
If you need enforcement at runtime, you add it explicitly. Pydantic validates data against a model built from hints, and libraries like beartype or typeguard check function calls as they happen. That's useful at system boundaries (API input, config files), not as a replacement for a static checker.
Python Type Hints Syntax: The Basics
Most of the hints you'll write fall into a handful of patterns.
Built-in types work directly: int, float, str, bool, bytes. Python treats int as acceptable where float is expected, which matches how numbers behave.
Containers take their element types in square brackets. Since Python 3.9 (PEP 585) you can use the built-in names; before that you imported List, Dict and friends from typing, which you'll still see in older code.
scores: list[int] = [90, 85]
ages: dict[str, int] = {"ada": 36}
point: tuple[float, float] = (1.0, 2.5) # exactly two floats
row: tuple[str, ...] = ("a", "b", "c") # any length, all str
tags: set[str] = {"python", "typing"}Unions say "one of these types". Since Python 3.10 (PEP 604) you write them with a pipe:
def parse(value: str | bytes) -> int: ...Abstract collection types from collections.abc let you accept more than one concrete type. If a function only loops over its argument, ask for Iterable[str] instead of list[str], and callers can pass a list, tuple, set or generator. Returning concrete types and accepting abstract ones is a good rule of thumb.
from collections.abc import Iterable, Mapping, Sequence
def total(prices: Iterable[float]) -> float:
return sum(prices)`Any` switches checking off for a value. It is an escape hatch, not a type to reach for by default; object is the stricter choice when you mean "anything, but I won't use it in type-specific ways".
Python Type Hints With Default Values and None
Python type hints with default values put the default after the annotation: name: type = default. Spaces go around the = when there's an annotation, which is the PEP 8 style.
def connect(host: str, port: int = 5432, timeout: float = 10.0) -> None:
...The most common gotcha is a default of None. The hint must say that None is allowed:
def find_user(user_id: int, cache: dict[int, str] | None = None) -> str | None:
if cache is None:
cache = {}
return cache.get(user_id)Optional[X] from typing means exactly the same as X | None. It doesn't mean "this argument is optional"; it means "this value may be None". Modern code prefers X | None because it says what it means. Older type checkers used to add | None implicitly when the default was None; mypy and Pyright no longer do that by default, so write it out.
A function that returns nothing gets -> None. A function that never returns at all (it always raises or exits) gets -> NoReturn or, on newer Pythons, -> Never.
For class attributes and variables, the same syntax applies. count: int without a value declares the type only; this is how dataclasses and Pydantic models define their fields.
Typing Functions, Callables and Classes
Callables. When a function takes another function, describe its signature with Callable[[arg types], return type]:
from collections.abc import Callable
def retry(fn: Callable[[], bytes], attempts: int = 3) -> bytes:
for _ in range(attempts - 1):
try:
return fn()
except OSError:
pass
return fn()Your own classes are types too. Annotate with the class name; since Python 3.14 you can reference a class inside its own body without quotes. On older versions, write the name as a string ("Node") or add from __future__ import annotations at the top of the file.
from typing import Self
class Node:
def __init__(self, value: int, next: "Node | None" = None) -> None:
self.value = value
self.next = next
def append(self, value: int) -> Self:
self.next = Node(value)
return selfSelf (Python 3.11, PEP 673) means "an instance of whatever class this method is called on", which keeps subclass return types correct.
Literal and Final. Literal["r", "w"] limits a value to exact constants, which is great for mode strings. Final marks a name that should never be reassigned.
TypedDict describes dictionaries with fixed keys, such as JSON payloads, without converting them into classes. Python 3.15 added closed=True and extra_items= (PEP 728) so you can say whether unknown keys are allowed.
from typing import Literal, TypedDict
class Event(TypedDict):
id: str
kind: Literal["click", "view"]
ts: floatGenerics, Protocols and Type Aliases
These are the features that make larger codebases pleasant to type.
Generics let one function or class work with many types while keeping them linked. Python 3.12 (PEP 695) added a short syntax for type parameters:
def first[T](items: list[T]) -> T:
return items[0]
class Box[T]:
def __init__(self, item: T) -> None:
self.item = itemThe checker now knows that first([1, 2]) returns an int and first(["a"]) a str. On Python 3.11 and older, you declare T = TypeVar("T") from typing first.
Protocols (PEP 544, Python 3.8) are structural types: "anything with these methods". They're how you type duck typing, and they avoid forcing callers to inherit from your base class.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown(resources: list[SupportsClose]) -> None:
for r in resources:
r.close()Any object with a close() method that takes no arguments and returns None matches, whether it's a file, a socket or your own class.
Type aliases give a long type a short name. Python 3.12 added the type statement for this:
type UserId = int
type JSON = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | NoneAnnotated attaches extra metadata to a type that tools can read at runtime. FastAPI and Pydantic use it heavily, for example Annotated[int, Field(gt=0)] for "a positive integer".
Type Checkers Compared: mypy, Pyright, Pyrefly and ty
A type checker is what turns hints into errors. All of them follow the shared typing specification, but they differ in speed, defaults and how far along they are.
| Checker | Made by | Written in | Status | Notes |
|---|---|---|---|---|
| mypy | Python community (started by Jukka Lehtosalo) | Python, compiled with mypyc | Stable, the reference checker | Most configuration options; plugins for Django, Pydantic and others |
| Pyright | Microsoft | TypeScript | Stable | Fast, strict modes; powers the Pylance extension in VS Code |
| Pyrefly | Meta | Rust | Stable since its 1.0 release in 2026 | Very fast on large codebases, includes a language server |
| ty | Astral (makers of uv and Ruff) | Rust | Beta | Extremely fast, built for editor use; not yet a full replacement |
| Pydantic, beartype, typeguard | Various | Python | Stable | Runtime validation, not static checking |
Pick one static checker for CI and stick with it, because the tools disagree on edge cases. mypy is the safe default and has the most documentation. Pyright is the natural pick if your team uses VS Code, since Pylance already runs it. The Rust-based checkers are worth trying on big monorepos where mypy takes minutes, though ty is still in beta. Teams that adopt ty for its editor speed usually keep an established checker as the merge gate.
Start lenient and tighten over time. mypy's --strict flag on day one of an untyped project produces thousands of errors and gets switched off again. Instead, check only annotated functions (the default), then enable stricter options per module as you add hints.
Which Python Version Added Which Type Hints?
The syntax you can use depends on the oldest Python version you support. As of late 2026, Python 3.10 has reached end of life, so most maintained projects can rely on everything up to 3.11.
| Python version | Typing feature | PEP |
|---|---|---|
| 3.5 | Function annotations get a standard meaning, typing module | 484 |
| 3.6 | Variable annotations (count: int = 0) | 526 |
| 3.7 | from __future__ import annotations (postponed evaluation) | 563 |
| 3.8 | Protocol, Literal, TypedDict, Final | 544, 586, 589, 591 |
| 3.9 | Built-in generics (list[int]), Annotated | 585, 593 |
| 3.10 | Pipe syntax for unions, ParamSpec, TypeAlias, TypeGuard | 604, 612, 613, 647 |
| 3.11 | Self, LiteralString, Required / NotRequired, variadic generics | 673, 675, 655, 646 |
| 3.12 | def f[T]() type parameters, type statement, @override | 695, 698 |
| 3.13 | Type parameter defaults, TypeIs, ReadOnly TypedDict items, @deprecated | 696, 742, 705, 702 |
| 3.14 | Lazy evaluation of annotations, annotationlib | 649, 749 |
| 3.15 | TypeForm, closed TypedDicts and extra_items, @disjoint_base | 747, 728, 800 |
If you support an older version than a feature needs, many of these are backported in the typing_extensions package, which type checkers understand.
Worked Example: Adding Type Hints to Real Code
Here's a small, untyped function of the kind every codebase has. It loads orders from a CSV file and totals them per customer.
import csv
def load_totals(path, min_amount=0):
totals = {}
with open(path) as f:
for row in csv.DictReader(f):
amount = float(row["amount"])
if amount >= min_amount:
totals[row["customer"]] = totals.get(row["customer"], 0) + amount
return totalsStep 1 is the signature. path could be a string or a pathlib.Path, the minimum is a number, and the result maps customer names to totals:
import csv
from pathlib import Path
def load_totals(path: str | Path, min_amount: float = 0.0) -> dict[str, float]:
totals: dict[str, float] = {}
with open(path, newline="") as f:
for row in csv.DictReader(f):
amount = float(row["amount"])
if amount >= min_amount:
totals[row["customer"]] = totals.get(row["customer"], 0.0) + amount
return totalsStep 2 is to run the checker and read what it reports. Annotating the empty dict makes the intent explicit: an empty {} says nothing about what it will hold, so a checker has to guess from later assignments, and when it can't, mypy stops with a "Need type annotation" error.
Step 3 is to let the hints catch a real bug. Suppose a caller later writes:
top = max(load_totals("orders.csv"), key=len)The intent was "the customer with the highest total", but max over a dict iterates its keys, so this returns the longest name. The hints don't flag that one, because it's type-correct. What they do flag is the next mistake a refactor makes, for example changing the return to list[tuple[str, float]] and forgetting a caller that still does totals["ada"]. The checker points at every broken call site at once, which is where type hints earn their keep.
Three habits from this example generalise: annotate signatures first, annotate empty containers, and accept the broadest input type you can handle (str | Path, Iterable) while returning a concrete one.
Python Type Hints vs Pydantic and Docstrings
People often ask how hints relate to two other ways of describing types.
Type hints vs Pydantic. Hints are checked statically and ignored at runtime. Pydantic reads the same hints at runtime and validates (and converts) incoming data, raising an error if a field is wrong. They complement each other: use plain hints throughout your code, and a Pydantic model where untrusted data enters, such as API requests or config files. FastAPI is built on exactly that split.
Type hints vs docstrings. Before hints, types lived in docstrings (:param name: str). Tools can't check those, and they drift out of date. With hints in the signature, keep docstrings for what types can't say: what the function does, units, side effects and examples. Doc generators such as Sphinx and mkdocstrings read the hints, so you don't repeat them.
Type hints vs TypeScript. The comparison comes up a lot, and the key difference is enforcement. TypeScript's compiler refuses to emit code with type errors by default, and types are part of the language. Python's hints are optional metadata and the interpreter never checks them. Our Python vs TypeScript comparison covers what that means for real projects.
Common Mistakes With Type Hints
- Using `Any` everywhere. Each
Anysilently disables checking for everything it touches. Preferobject, aProtocolor a union. - Forgetting `| None`. A default of
NoneneedsX | Nonein the hint, or the checker treats the value as always present. - Over-specific arguments. Asking for
list[str]when you only iterate forces callers to convert tuples and generators. UseIterable[str]orSequence[str]. - Mutable defaults.
def f(items: list[str] = [])shares one list across calls. UseNoneas the default and create the list inside. - Silencing instead of fixing.
# type: ignoreshould be rare and specific (# type: ignore[arg-type]), with a reason nearby. - Expecting runtime checks. Hints don't validate input. Validate data at the boundaries with Pydantic or explicit checks.
- Turning on strict mode too early. Adopt gradually: signatures first, CI second, strict options module by module.
Hints pair well with the rest of a modern Python toolchain. A fast package manager like the ones in our uv vs pip guide plus Ruff for linting and one type checker in CI make a tidy setup.
Python Type Hints Cheat Sheet
| You want to say | Write | Since |
|---|---|---|
| A simple value | x: int, name: str, ok: bool | 3.6 |
| A list of strings | list[str] | 3.9 |
| A dict from str to int | dict[str, int] | 3.9 |
| Exactly two floats | tuple[float, float] | 3.9 |
| A tuple of any length | tuple[int, ...] | 3.9 |
| One of several types | Union[int, str], or a pipe between the types on 3.10+ | 3.5 |
| Maybe None | Optional[str], or str piped with None on 3.10+ | 3.5 |
| Any iterable of str | Iterable[str] from collections.abc | 3.9 |
| A function taking int, returning str | Callable[[int], str] | 3.9 |
| Returns nothing | -> None | 3.5 |
| Exact constant values | Literal["r", "w"] | 3.8 |
| Dict with fixed keys | class Row(TypedDict): ... | 3.8 |
| Anything with a method | class P(Protocol): ... | 3.8 |
| Same type in and out | def f[T](x: T) -> T | 3.12 |
| A named type alias | type UserId = int | 3.12 |
| The current class | -> Self | 3.11 |
| Value with metadata | Annotated[int, ...] | 3.9 |
| Opt out of checking | Any | 3.5 |
For a longer reference, the mypy documentation keeps a cheat sheet, and the typing specification at typing.python.org is the authoritative source for how checkers should behave. If you're choosing between languages for a new service, our Go vs Python comparison explains how Go's built-in static types compare with Python's optional ones.
FAQ
Do type hints make Python faster?
No. CPython doesn't use hints to optimise code, and since Python 3.14 annotations are evaluated lazily, so they cost almost nothing at import time either. Some compilers, such as mypyc and Cython, can use type information to generate faster code, but that's a separate build step.
When were type hints added to Python?
Function annotations as syntax arrived in Python 3.0, but type hints in today's sense came with PEP 484 in Python 3.5 (2015), which defined the typing module and what annotations mean. Variable annotations followed in Python 3.6.
Should I use Optional[X] or X | None?
They mean the same thing. Use X | None if you support Python 3.10 or newer, because it's shorter and clearer; Optional still works and is common in older code.
Do I need to annotate every variable?
No. Type checkers infer most local variable types from the assigned value. Annotate function signatures, class attributes, empty containers and anything the checker can't infer, and leave obvious locals alone.
How do I add type hints to an existing project?
Start with the most-used modules and annotate public function signatures. Add a type checker to CI with lenient settings, fix what it finds, then tighten options per module. Libraries without hints often have stub packages (named like types-requests) that supply them.