Programming languages · Intermediate · 20 min
Add type hints to Python code and check them with mypy
By Padding · Updated 18 Nov 2026
Python 3.15.2 · mypy 2.4.1 · uv 0.13 (python:3.15-slim)
You will type a small order-totals script one layer at a time, let mypy 2.4 find a None bug before the code runs, and finish with a strict mypy setup in pyproject.toml.
On this page
Type hints are notes in your code that say what kind of value a variable holds or a function takes and returns: qty: int, -> float. Python itself ignores them when the program runs. A separate tool, a type checker, reads them and reports places where the code does not agree with itself. mypy is the original Python type checker and is still the most widely used one.
In this tutorial you start from a short script that totals shop orders. It works for every order you try, but it has a bug that crashes it when someone asks for an order that does not exist. You add hints one layer at a time, and mypy points at the bug before you ever run the bad case. By the end the script uses X | None, TypedDict, a Protocol, a generic function written with the Python 3.12+ def first[T] syntax and a type alias, and the project checks itself in strict mode.
Once mypy is installed it runs entirely on your machine, so checking again after every change costs no data. That matters if you work on prepaid mobile data.
Step 1 · Create the project and the untyped script
Make a throwaway project folder, create a bare pyproject.toml and add mypy. The range allows 2.4 patch releases and nothing newer, because a new mypy minor release can report new errors on code that passed before:
mkdir -p ~/types-demo
cd ~/types-demo
uv init --bare
uv add --dev "mypy>=2.4,<2.5"--bare writes only pyproject.toml, with no sample main.py. --dev records mypy as a development tool, not something the script needs to run.
Now add some sample orders and the script. Each order has an ID, a customer and lines of stock codes (SKUs) with quantities. Prices sit in a dictionary in the script:
cat > orders.json <<'JSON'
[
{"id": 1, "customer": "Amara", "lines": [{"sku": "TEA", "qty": 2}, {"sku": "MUG", "qty": 1}]},
{"id": 2, "customer": "Tunde", "lines": [{"sku": "BEANS", "qty": 3}]}
]
JSON
cat > orders.py <<'PY'
import json
import sys
PRICES = {"TEA": 4.50, "MUG": 8.00, "BEANS": 12.25}
def load_orders(path):
with open(path) as f:
return json.load(f)
def find_order(orders, order_id):
for order in orders:
if order["id"] == order_id:
return order
return None
def line_total(sku, qty):
return PRICES[sku] * qty
def order_total(order):
total = 0.0
for line in order["lines"]:
total += line_total(line["sku"], line["qty"])
return total
def item_count(quantities):
return sum(quantities)
def report(orders, order_id):
order = find_order(orders, order_id)
count = item_count([line["qty"] for line in order["lines"]])
return f"Order {order_id} for {order['customer']}: {count} items, {order_total(order):.2f}"
if __name__ == "__main__":
orders = load_orders("orders.json")
print(report(orders, int(sys.argv[1])))
PY
uv run orders.py 1
uv run orders.py 2Check it worked
The two runs print Order 1 for Amara: 3 items, 17.00 and Order 2 for Tunde: 3 items, 36.75. Nothing looks wrong yet.
Step 2 · Run mypy on code with no hints
Point mypy at the script before you change anything:
uv run mypy --version
uv run mypy orders.pyCheck it worked
The first line shows mypy 2.4.1 (or a later 2.4 release). The second says Success: no issues found in 1 source file.
That success is not a clean bill of health. By default mypy does not check the inside of a function that has no annotations at all, so that you can add types to an existing codebase gradually without a wall of errors on day one. Untyped code is invisible to it. The next step gives it something to read.
Step 3 · Annotate functions and variables
Annotate every parameter and return value, and the two variables whose type is worth stating. The new pieces:
PRICES: dict[str, float]says the keys are strings and the values are floats.quantities: list[int]says the function takes a list of whole numbers.dict[str, Any]is a stand-in for one order for now: a dictionary with string keys and values of any type.Anyswitches checking off for whatever it touches. You replace it in a later step.find_orderreturnsdict[str, Any] | None. The| Noneis the honest part: the function really does returnNonewhen nothing matches, and now the signature says so.
Replace orders.py with the annotated version:
cat > orders.py <<'PY'
import json
import sys
from typing import Any
PRICES: dict[str, float] = {"TEA": 4.50, "MUG": 8.00, "BEANS": 12.25}
def load_orders(path: str) -> list[dict[str, Any]]:
with open(path) as f:
return json.load(f)
def find_order(orders: list[dict[str, Any]], order_id: int) -> dict[str, Any] | None:
for order in orders:
if order["id"] == order_id:
return order
return None
def line_total(sku: str, qty: int) -> float:
return PRICES[sku] * qty
def order_total(order: dict[str, Any]) -> float:
total: float = 0.0
for line in order["lines"]:
total += line_total(line["sku"], line["qty"])
return total
def item_count(quantities: list[int]) -> int:
return sum(quantities)
def report(orders: list[dict[str, Any]], order_id: int) -> str:
order = find_order(orders, order_id)
count = item_count([line["qty"] for line in order["lines"]])
return f"Order {order_id} for {order['customer']}: {count} items, {order_total(order):.2f}"
if __name__ == "__main__":
orders = load_orders("orders.json")
print(report(orders, int(sys.argv[1])))
PYRun mypy again:
uv run mypy orders.pyCheck it worked
mypy now fails with three errors, all in report:
orders.py:37: error: Value of type "dict[str, Any] | None" is not indexable [index]
orders.py:38: error: Value of type "dict[str, Any] | None" is not indexable [index]
orders.py:38: error: Argument 1 to "order_total" has incompatible type "dict[str, Any] | None"; expected "dict[str, Any]" [arg-type]
Found 3 errors in 1 file (checked 1 source file)This is the hidden bug. report uses the result of find_order as if it were always an order, but the signature you just wrote says it can be None. The word in square brackets at the end of each line is the error code, which you will use later. To see the bug is real, ask for an order that does not exist:
uv run orders.py 3The script stops with TypeError: 'NoneType' object is not subscriptable. mypy found that without running anything.
Step 4 · Narrow the None away with an if check
Inside report, the type of order is dict[str, Any] | None. After if order is None: return ..., mypy knows the rest of the function can only see a dictionary. That is called narrowing: a check in the code makes a wide type narrower. Add the check to report and leave the rest of the file alone:
cat > orders.py <<'PY'
import json
import sys
from typing import Any
PRICES: dict[str, float] = {"TEA": 4.50, "MUG": 8.00, "BEANS": 12.25}
def load_orders(path: str) -> list[dict[str, Any]]:
with open(path) as f:
return json.load(f)
def find_order(orders: list[dict[str, Any]], order_id: int) -> dict[str, Any] | None:
for order in orders:
if order["id"] == order_id:
return order
return None
def line_total(sku: str, qty: int) -> float:
return PRICES[sku] * qty
def order_total(order: dict[str, Any]) -> float:
total: float = 0.0
for line in order["lines"]:
total += line_total(line["sku"], line["qty"])
return total
def item_count(quantities: list[int]) -> int:
return sum(quantities)
def report(orders: list[dict[str, Any]], order_id: int) -> str:
order = find_order(orders, order_id)
if order is None:
return f"Order {order_id} not found"
count = item_count([line["qty"] for line in order["lines"]])
return f"Order {order_id} for {order['customer']}: {count} items, {order_total(order):.2f}"
if __name__ == "__main__":
orders = load_orders("orders.json")
print(report(orders, int(sys.argv[1])))
PY
uv run mypy orders.py
uv run orders.py 3isinstance(x, str), if x: and an early return or raise all narrow types the same way. Write is None when you mean "missing": if not order also treats an empty dictionary as missing, which is a different rule.
Check it worked
mypy prints Success: no issues found in 1 source file and the script prints Order 3 not found instead of crashing.
Step 5 · Describe the JSON record with TypedDict
dict[str, Any] still hides mistakes. A typo such as order["custmer"] passes, because any string key is allowed and the value is Any. A TypedDict lists the exact keys a dictionary has and the type of each one. It is still a plain dictionary at runtime, so JSON loads into it unchanged.
Define Line and Order and use them in place of dict[str, Any]:
cat > orders.py <<'PY'
import json
import sys
from typing import TypedDict
class Line(TypedDict):
sku: str
qty: int
class Order(TypedDict):
id: int
customer: str
lines: list[Line]
PRICES: dict[str, float] = {"TEA": 4.50, "MUG": 8.00, "BEANS": 12.25}
def load_orders(path: str) -> list[Order]:
with open(path) as f:
return json.load(f)
def find_order(orders: list[Order], order_id: int) -> Order | None:
for order in orders:
if order["id"] == order_id:
return order
return None
def line_total(sku: str, qty: int) -> float:
return PRICES[sku] * qty
def order_total(order: Order) -> float:
total: float = 0.0
for line in order["lines"]:
total += line_total(line["sku"], line["qty"])
return total
def item_count(quantities: list[int]) -> int:
return sum(quantities)
def report(orders: list[Order], order_id: int) -> str:
order = find_order(orders, order_id)
if order is None:
return f"Order {order_id} not found"
count = item_count([line["qty"] for line in order["lines"]])
return f"Order {order_id} for {order['customer']}: {count} items, {order_total(order):.2f}"
if __name__ == "__main__":
orders = load_orders("orders.json")
print(report(orders, int(sys.argv[1])))
PY
uv run mypy orders.py
uv run orders.py 1Now make the typo on purpose in a scratch file:
cat > typo.py <<'PY'
from orders import Order
def greet(order: Order) -> str:
return "Hello " + order["custmer"]
PYuv run mypy typo.pyCheck it worked
orders.py passes and still prints Order 1 for Amara: 3 items, 17.00. typo.py fails with error: TypedDict "Order" has no key "custmer" [typeddict-item] and a note asking Did you mean "customer"?. Delete the scratch file:
rm typo.pyOne honest gap remains: mypy trusts that orders.json really has this shape. json.load returns Any, so a file with a missing key would still get through. Strict mode, two steps on, makes that gap visible.
Step 6 · Accept anything with a total() method using Protocol
A checkout adds up more than orders: a delivery fee, a basket, perhaps a service charge later. They are unrelated classes, and you do not want them to inherit from a common base just to satisfy the checker. A Protocol describes a shape instead: "anything with a total() method that returns a float". Any class with that method matches, without naming the protocol.
cat > totals.py <<'PY'
from typing import Protocol
from orders import Order, order_total
class HasTotal(Protocol):
def total(self) -> float: ...
class Basket:
def __init__(self, order: Order) -> None:
self.order = order
def total(self) -> float:
return order_total(self.order)
class DeliveryFee:
def __init__(self, zone: str) -> None:
self.zone = zone
def total(self) -> float:
return 5.00 if self.zone == "local" else 9.50
def grand_total(items: list[HasTotal]) -> float:
return sum(item.total() for item in items)
if __name__ == "__main__":
order: Order = {"id": 9, "customer": "Wanjiru", "lines": [{"sku": "TEA", "qty": 4}]}
print(f"{grand_total([Basket(order), DeliveryFee('local')]):.2f}")
PY
uv run mypy totals.py
uv run totals.pyThen pass something that does not fit. A Voucher has an amount() method, not total():
cat > wrong_total.py <<'PY'
from totals import DeliveryFee, grand_total
class Voucher:
def amount(self) -> float:
return 2.00
print(grand_total([DeliveryFee("local"), Voucher()]))
PYuv run mypy wrong_total.pyCheck it worked
totals.py passes mypy and prints 23.00 (four teas at 4.50 plus a 5.00 fee). wrong_total.py fails with an error that ends something like List item 1 has incompatible type "Voucher"; expected "HasTotal" [list-item]. Delete it:
rm wrong_total.pyStep 7 · Write a generic function and type aliases
first returns the first item of a sequence, or None if it is empty. It works for a list of IDs, a list of names or a list of orders, and you want the caller to get back the same type they passed in. The Python 3.12+ syntax puts a type parameter in square brackets after the function name: def first[T](items: Sequence[T]) -> T | None. T stands for "whatever type the items are".
The type statement, also Python 3.12+, gives a name to a type so that a signature reads as what it means. type OrderId = int is still an int to mypy, but list[OrderId] tells the next reader what the numbers are.
cat > generics.py <<'PY'
from collections.abc import Sequence
from orders import PRICES, Order, load_orders
type OrderId = int
type Catalogue = dict[str, float]
def first[T](items: Sequence[T]) -> T | None:
return items[0] if items else None
def cheapest(catalogue: Catalogue) -> str | None:
return first(sorted(catalogue, key=catalogue.__getitem__))
def order_ids(orders: list[Order]) -> list[OrderId]:
return [order["id"] for order in orders]
if __name__ == "__main__":
orders = load_orders("orders.json")
print(first(order_ids(orders)))
print(cheapest(PRICES))
print(first([]))
PY
uv run mypy generics.py
uv run generics.pyTo see what mypy worked out for T at each call, use reveal_type. It is a request to the checker, so keep it in a file you only give to mypy:
cat > reveal.py <<'PY'
from generics import first
reveal_type(first([3, 1, 2]))
reveal_type(first(["TEA", "MUG"]))
PY
uv run mypy reveal.py
rm reveal.pyCheck it worked
generics.py passes and prints 1, TEA and None. The reveal.py run prints two notes, Revealed type is "int | None" and Revealed type is "str | None", then Success. The same function gave back a different type for each input.
Step 8 · Turn on strict mode in pyproject.toml
So far you have checked one file at a time with mypy's relaxed defaults. Put the settings in pyproject.toml so that a bare uv run mypy checks the whole project the same way every time. strict = true turns on a group of stricter checks, including errors for any function left without annotations and for Any leaking out of a function that promised a real type:
cat >> pyproject.toml <<'TOML'
[tool.mypy]
files = ["orders.py", "totals.py", "generics.py"]
strict = true
TOMLuv run mypyStrict mode finds the gap from the TypedDict step: error: Returning Any from function declared to return "list[Order]" [no-any-return]. json.load returns Any, and load_orders passes it on while claiming a list of orders.
There are three ways to answer it, and they say different things:
- Validate the data (check every key and type, or use a library such as Pydantic). That is the right answer for input from users or other systems.
- Use
cast(list[Order], ...). It does nothing at runtime. It is a written promise that you know the shape, which is fair for a file your own program wrote. - Add
# type: ignore[no-any-return]. It silences that one error code on that one line.
orders.json is a sample file you control, so use cast. Add it to the import and the return line by rewriting load_orders in place with Python, which works the same on Linux and macOS:
uv run python - <<'PY'
from pathlib import Path
path = Path("orders.py")
text = path.read_text()
text = text.replace("from typing import TypedDict\n", "from typing import TypedDict, cast\n", 1)
text = text.replace(" return json.load(f)\n", " return cast(list[Order], json.load(f))\n", 1)
path.write_text(text)
PY
grep -n "cast" orders.py
uv run mypyCheck it worked
grep shows two lines that use cast, and uv run mypy prints Success: no issues found in 3 source files. The run checked all three files without you naming them.
Step 9 · Know when a type: ignore is honest
A # type: ignore is honest when the type error is the point, or when the checker cannot know something you can, and the comment says why. Always add the error code in brackets so that the comment silences only that error and nothing else that turns up on the line later. Strict mode also reports ignores that no longer silence anything, so they cannot pile up unnoticed.
Write a file with one ignore of each kind:
cat > ignores.py <<'PY'
from orders import line_total
# Honest: passing the wrong type is the point of this check.
try:
line_total("TEA", "2") # type: ignore[arg-type]
except TypeError as err:
print("TypeError:", err)
# Stale: nothing is wrong on this line any more.
tea: float = line_total("TEA", 2) # type: ignore[arg-type]
PY
uv run python ignores.pyuv run mypy ignores.pyNaming a file on the command line overrides the files list, but mypy still reads strict = true from pyproject.toml.
Notice what the Python run did. Type hints are not checked when the program runs: line_total("TEA", "2") was called with a string, and the only error came from the multiplication inside it. A call that does not crash is worse. Asking report for order "1" as a string returns Order 1 not found, because "1" never equals 1, and nothing complains until mypy reads the code:
cat > runtime.py <<'PY'
from orders import load_orders, report
print(report(load_orders("orders.json"), "1"))
PY
uv run python runtime.pyuv run mypy runtime.pyCheck it worked
The Python run of ignores.py prints TypeError: can't multiply sequence by non-int of type 'float'. mypy on ignores.py reports only line 10, Unused "type: ignore" comment [unused-ignore], so the honest ignore on line 5 did its job and the stale one was caught. runtime.py prints Order 1 not found, and mypy rejects it with Argument 2 to "report" has incompatible type "str"; expected "int". In your own code, delete a stale ignore as soon as mypy reports it.
Step 10 · Clean up
Remove the demo project, including the .venv and .mypy_cache folders inside it. Python and uv stay installed:
cd ~
rm -rf ~/types-demoCheck it worked
ls ~/types-demo reports No such file or directory.
Next steps
- Run mypy alongside your tests, so both gate a change: write and run tests with pytest.
- Replace the order dictionaries with classes that carry their own types: model records in Python with dataclasses.
- Keep the
[tool.mypy]section in a project that others install: package a Python project with uv and pyproject.toml. - Go back over how Python itself treats values and types: understand values and types in Python.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials