Skip to main content

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:

Bash
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:

Bash
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 2

Check 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:

Bash
uv run mypy --version
uv run mypy orders.py

Check 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. Any switches checking off for whatever it touches. You replace it in a later step.
  • find_order returns dict[str, Any] | None. The | None is the honest part: the function really does return None when nothing matches, and now the signature says so.

Replace orders.py with the annotated version:

Bash
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])))
PY

Run mypy again:

Bash
uv run mypy orders.py

Check it worked

mypy now fails with three errors, all in report:

Text
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:

Bash
uv run orders.py 3

The 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:

Bash
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 3

isinstance(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]:

Bash
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 1

Now make the typo on purpose in a scratch file:

Bash
cat > typo.py <<'PY'
from orders import Order


def greet(order: Order) -> str:
    return "Hello " + order["custmer"]
PY
Bash
uv run mypy typo.py

Check 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:

Bash
rm typo.py

One 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.

Bash
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.py

Then pass something that does not fit. A Voucher has an amount() method, not total():

Bash
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()]))
PY
Bash
uv run mypy wrong_total.py

Check 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:

Bash
rm wrong_total.py

Step 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.

Bash
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.py

To 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:

Bash
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.py

Check 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:

Bash
cat >> pyproject.toml <<'TOML'

[tool.mypy]
files = ["orders.py", "totals.py", "generics.py"]
strict = true
TOML
Bash
uv run mypy

Strict 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:

  1. 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.
  2. 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.
  3. 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:

Bash
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 mypy

Check 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:

Bash
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.py
Bash
uv run mypy ignores.py

Naming 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:

Bash
cat > runtime.py <<'PY'
from orders import load_orders, report

print(report(load_orders("orders.json"), "1"))
PY
uv run python runtime.py
Bash
uv run mypy runtime.py

Check 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:

Bash
cd ~
rm -rf ~/types-demo

Check it worked

ls ~/types-demo reports No such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.