Core Python·Lesson 17 of 67·intermediate
Type hints and static checking with mypy
Annotate what your functions accept and return, model JSON payloads with TypedDict, describe duck typing with Protocol — and let mypy find the bug before you run anything.
In this lesson · 18 min
- →Annotate parameters, returns, variables and collections
- →Express optional and alternative types with the | operator
- →Model a JSON payload with TypedDict and an interface with Protocol
- →Explain why hints are not enforced at runtime
- →Run mypy and read what it tells you
Type hints are notes to your reader and your tools about what a function accepts and returns. Python does not enforce them; a checker does, before the code ever runs.
Annotating
Collections say what they hold. Built-in generics have worked since Python 3.9, so you need no imports for the common cases:
A tuple of fixed length spells out each position; tuple[str, ...] means “any number, all
strings”:
Optional and alternatives
X | None is the type of “an X, or nothing”. Writing it is what forces you to handle the
None case:
The same | expresses any alternative:
Functions as parameters
Callable describes a function’s shape — its arguments and its return type:
Take Iterable when you only intend to loop once, and return Iterator from a generator.
Accepting Iterable rather than list means a caller can hand you a generator.
TypedDict
JSON arrives as a dictionary, and dict[str, Any] tells a reader nothing. TypedDict gives
that dictionary a shape without changing it into a class:
Protocol
Protocol describes what an object must do, not what it inherits from. It is duck typing that
a checker can verify:
Neither class inherits from Retriever. They satisfy it by having the right method — which is
exactly how you want to describe “anything that can retrieve”.
Literal and type aliases
Literal restricts a value to a fixed set, so a typo in a model name is caught by the checker
rather than by a 400 from the API. A type alias names a shape you use repeatedly.
Hints are not enforced
This runs perfectly happily, which is the whole point of needing a checker:
Running mypy
Install it into your project’s environment and point it at your code:
pip install mypy
mypy src/
For the function above, it reports the bug without running anything:
src/tokens.py:5: error: Argument 1 to "add_tokens" has incompatible type "str";
expected "int" [arg-type]
Found 1 error in 1 file (checked 1 source file)
Turn the strictness up as the codebase allows, in pyproject.toml:
[tool.mypy]
python_version = "3.13"
strict = true
warn_unreachable = true
[[tool.mypy.overrides]]
module = ["some_untyped_library.*"]
ignore_missing_imports = true
Try it yourself
Annotate summarise fully: it takes a list of strings and an optional integer limit, and returns a string or None when there is nothing to summarise.
Define a Document TypedDict with id: str, text: str and an optional tokens: int, then annotate load to return a list of them.
Check yourself
What happens at runtime when you call a function annotated -> int with a string argument?
Check yourself
Why use Protocol rather than a base class for 'anything that can search'?
Recap
- Annotate parameters and returns:
def f(text: str, size: int = 20) -> int:. - Built-in generics need no imports:
list[str],dict[str, float],tuple[str, int]. X | Noneis the optional type, and aNonedefault must say so.Callable,IterableandIteratordescribe functions and streams; acceptIterable, returnIterator.TypedDictgives a JSON payload a shape;Protocoldescribes behaviour without inheritance;Literalpins a value to a fixed set.- Nothing is enforced at runtime — that is what
mypyis for, and Pydantic when you need real validation.