Type hints and mypy

15 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

What type hints are, and are not

Type hints are labels that say what type a variable, parameter or return value should be. Python itself ignores them when running. They are for people and for tools. A tool called a type checker reads them and warns you when your code does not add up, before you run anything. The most widely used one is mypy.

I resisted adding types for a long time. What changed my mind was a refactor of a billing script: mypy found six places where I passed a string where a number was expected, and none of them had a test.

The basics

def total_price(unit_price: float, quantity: int) -> float:
    return unit_price * quantity

name: str = "Tea"
prices: list[float] = [120.0, 99.5]
stock: dict[str, int] = {"tea": 10}
point: tuple[float, float] = (31.5, 74.3)

Since Python 3.9 you can use the built-in names list, dict, set and tuple with square brackets. You no longer need typing.List and friends. A function that returns nothing is annotated -> None.

Optional values and unions

A value that might be missing has the type X | None (Python 3.10 and later). The same | sign joins any types.

from dataclasses import dataclass
from typing import Protocol, TypedDict


class Row(TypedDict):
    sku: str
    price: float
    qty: int


@dataclass
class Product:
    sku: str
    name: str
    price: float


CATALOG: dict[str, Product] = {
    "T1": Product("T1", "Tea", 120.0),
    "S1": Product("S1", "Sugar", 150.0),
}


def find_product(sku: str) -> Product | None:
    return CATALOG.get(sku)


def line_total(row: Row) -> float:
    product = find_product(row["sku"])
    if product is None:
        raise KeyError(f"unknown sku {row['sku']}")
    return product.price * row["qty"]


class Sender(Protocol):
    def send(self, to: str, text: str) -> None: ...


def notify_total(sender: Sender, to: str, rows: list[Row]) -> float:
    total = sum(line_total(r) for r in rows)
    sender.send(to, f"Your total is {total:.2f}")
    return total


class PrintSender:
    def send(self, to: str, text: str) -> None:
        print(f"to {to}: {text}")


rows: list[Row] = [{"sku": "T1", "price": 120.0, "qty": 2}, {"sku": "S1", "price": 150.0, "qty": 1}]
notify_total(PrintSender(), "ali@example.com", rows)

Output: to ali@example.com: Your total is 390.00

What the checker understands here

find_product may return None. If we wrote return find_product(sku).price, mypy would complain: Item "None" of "Product | None" has no attribute "price". That is precisely the bug that crashes programs in production. After the if product is None: raise line, mypy knows product is a real Product. This is called narrowing.

A TypedDict describes a dictionary with a known set of string keys. It helps when you work with JSON-like data. At runtime it is still a plain dict. A Protocol describes behaviour: PrintSender never mentions Sender, yet mypy accepts it because it has a matching send method.

Generics

Since Python 3.12 you can declare generic functions and classes with the new syntax:

def first[T](items: list[T]) -> T:
    return items[0]

class Box[T]:
    def __init__(self, value: T) -> None:
        self.value = value

Now first([1, 2]) is known to return an int, and first(["a"]) a str. On older versions, the same thing is written with TypeVar from typing.

Running mypy

pip install mypy
mypy shop.py
mypy --strict src/

A clean run prints Success: no issues found in 1 source file. Start without --strict on an existing project, add types to the most important modules first, and tighten the settings later. You can configure mypy in pyproject.toml under [tool.mypy].

Common mistakes and tips

  • Using Any everywhere. Any turns checking off for that value. It is sometimes needed, but each one is a hole in your safety net.
  • Treating hints as validation. A hint does not stop total_price("a", 2) at run time. If data comes from outside, such as JSON or user input, validate it. Libraries like pydantic do this for you.
  • Annotating a mutable default wrongly. def f(x: list[int] = []) still has the shared-list problem.
  • Silencing errors with # type: ignore without understanding them. Add the specific error code and a comment explaining why.
  • Returning None on one path. If a function sometimes returns a value and sometimes nothing, the checker will tell you. Fix the return type, or make all paths return.

Where types pay off most

Types are worth the effort at the boundaries: function signatures, data structures passed between modules, and public APIs. Inside a short function, mypy can infer local variables, so you rarely need to annotate them. Your editor also gets better: autocomplete and rename work much more reliably when types are known.

Try it yourself

Take one of your older scripts, or the expense tracker from the beginner course, and add annotations to every function. Run mypy on it. Fix everything it reports, and note which problems were real bugs and which were just missing information. Then try mypy --strict and see how much more it asks for.

python
from dataclasses import dataclass
from typing import Protocol, TypedDict


class Row(TypedDict):
    sku: str
    price: float
    qty: int


@dataclass
class Product:
    sku: str
    name: str
    price: float


CATALOG: dict[str, Product] = {
    "T1": Product("T1", "Tea", 120.0),
    "S1": Product("S1", "Sugar", 150.0),
}


def find_product(sku: str) -> Product | None:
    return CATALOG.get(sku)


def line_total(row: Row) -> float:
    product = find_product(row["sku"])
    if product is None:
        raise KeyError(f"unknown sku {row['sku']}")
    return product.price * row["qty"]


class Sender(Protocol):
    def send(self, to: str, text: str) -> None: ...


def notify_total(sender: Sender, to: str, rows: list[Row]) -> float:
    total = sum(line_total(r) for r in rows)
    sender.send(to, f"Your total is {total:.2f}")
    return total


class PrintSender:
    def send(self, to: str, text: str) -> None:
        print(f"to {to}: {text}")


rows: list[Row] = [{"sku": "T1", "price": 120.0, "qty": 2}, {"sku": "S1", "price": 150.0, "qty": 1}]
notify_total(PrintSender(), "ali@example.com", rows)

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account