Type hints¶
Python is dynamically typed — the interpreter doesn't check your variable types. Type hints are annotations that describe the types you intend a function or variable to have, so a separate tool (a type-checker like mypy or pyright) can flag mismatches before the code runs. Your editor uses them too, for better autocomplete and inline warnings.
This guide takes type hints from "I've seen those -> arrows in other people's code" to "I can type my own functions, data structures, and gradual-typing a legacy module".
Sections¶
- Learn — four notebooks: why bother, basic annotations, generics over built-in collections, and the trickier bits (
Optional,Union,Literal,Callable,TypedDict). - Recipes — typing a function signature, typing a data structure, handling
Nonecleanly, and the mistakes that trip people up. - Reference — the
typingmodule, the built-in generic forms (list[int],dict[str, int], etc.), and a compact mypy cheatsheet. - Concepts — short essays on when type hints help and what gradual typing actually buys you.
If you're new to type hints, start with Learn → Why type hints. If you're here for a specific question, Recipes is task-focused, Reference is for lookups.
Python version note¶
This guide assumes Python 3.10+. Two features matter:
- The
X | Yunion syntax (int | str) andX | Nonefor optionals work in 3.10+. Earlier versions needUnion[int, str]andOptional[X]from thetypingmodule. - Built-in generics (
list[int],dict[str, int]) work in 3.9+. Before that you'd writeList[int],Dict[str, int]fromtyping.
Most UK university environments ship Python 3.10 or later. If you're stuck on older Python, the typing reference page shows the older equivalents.