Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 149 ยท Beyond the Basics

Static Type Checking with mypy

Learn to check Python types with mypy. Run the checker, read its errors, narrow Optional values, write generics and Protocols, and configure strict mode in pyproject.toml.

Python never checks type hints while your program runs. You can annotate a parameter as int and happily pass a string; nothing happens until some line fails far away from the real mistake. A static type checker closes that gap. It reads your code without running it, follows the types through every function call and reports places where they cannot fit together. mypy is the original and most widely used checker. Others, such as pyright, ty and pyrefly, follow the same typing rules.

The Type Hints lesson taught you how to write annotations. This lesson is about putting them to work: running mypy, reading its messages, fixing the common errors, using generics and Protocols in real code, and configuring the checker for a project. mypy is a tool you install and run on your computer, so its commands and output are shown in read-only blocks (every one was run with mypy 2). The runnable editors on this page show what hints do and do not do at runtime.

Running mypy

Install it in a virtual environment and point it at a file or a folder:

TEXT
python -m pip install mypy
python -m mypy app.py
python -m mypy src/           # a whole package or folder

If everything fits, mypy prints Success: no issues found in 1 source file. Otherwise each problem is reported as file:line: error: message [error-code]. The bracketed code names the kind of mistake and is useful for searching and for silencing.

flowchart LR
    A["Your .py files<br/>with type hints"] --> B["mypy reads the code<br/>(never runs it)"]
    B --> C["Infers and checks types"]
    C -->|"all consistent"| D["Success: no issues found"]
    C -->|"mismatch"| E["file:line: error [code]"]

mypy only analyzes your source; it never executes your program, so it is fast and safe to run in CI.

Reading the errors

Here is a file with several typical mistakes, saved as basics.py:

Python
def greet(name: str, times: int = 1) -> str:
    return ", ".join([f"Hello {name}"] * times)


greet("Ada", "3")
greet(42)
result: int = greet("Bob")
print(greet("Cy").upper().foo())


def find_user(user_id: int) -> str | None:
    return None if user_id < 0 else "ada"


name = find_user(3)
print(name.upper())
if name is not None:
    print(name.upper())

Running python -m mypy basics.py reports:

TEXT
basics.py:5: error: Argument 2 to "greet" has incompatible type "str"; expected "int"  [arg-type]
basics.py:6: error: Argument 1 to "greet" has incompatible type "int"; expected "str"  [arg-type]
basics.py:7: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]
basics.py:8: error: "str" has no attribute "foo"  [attr-defined]
basics.py:16: error: Item "None" of "str | None" has no attribute "upper"  [union-attr]
Found 5 errors in 1 file (checked 1 source file)

Lines 5 and 6 pass the wrong argument types. Line 7 stores a str in an int variable. Line 8 calls a method that does not exist (a typo mypy would otherwise leave for runtime). The last one is the most common real-world error: find_user may return None, so calling .upper() on the result is unsafe. Line 18, inside if name is not None:, is fine: mypy narrows the type there.

Narrowing types

After a check, mypy knows more about a value than its declared type says. These checks all narrow:

  • if x is not None: and if x: remove None from X | None.
  • isinstance(x, int) narrows a union to the matching member in the if branch and to the rest in the else branch.
  • assert x is not None narrows for the rest of the function (and also fails loudly at runtime).
  • Early returns: if x is None: return narrows everything after it.

A reveal_type(x) call is a debugging aid that only mypy understands: it prints the type mypy has inferred. Remove it before running the program, because it does not exist at runtime. For the function

Python
def parse(raw: str) -> int | str:
    return int(raw) if raw.isdigit() else raw


value = parse("12")
print(value + 1)
if isinstance(value, int):
    reveal_type(value)
else:
    reveal_type(value)

mypy reports an error on value + 1 (an int | str cannot be added to an int), then Revealed type is "int" in the first branch and Revealed type is "str" in the second. The runtime code does the same isinstance check, so narrowing is both a typing feature and plain Python.

Annotations have no effect while the program runs, which is why the checker is needed. Try it:

Python Hints are not enforced at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

double("ab") returns "abab", which breaks the promise -> int but raises nothing. mypy would flag both bad calls before you ever run the program.

Inference and the untyped-code problem

You do not annotate everything. mypy infers the type of local variables from their values (count = 0 is an int), so annotate function signatures and let the rest be inferred. What it does not do is infer a function's signature. By default mypy skips the body of any function that has no annotations at all, treating its parameters and result as Any, a type that silently matches everything. That is why gradual adoption works: you can add hints one function at a time. Strict mode, covered below, turns the leniency off.

With these three functions in loose.py:

Python
def add(a, b):
    return a + b


def scale(x: float, factor):
    return x * factor

default mypy reports nothing about them, while python -m mypy --strict loose.py complains:

TEXT
loose.py:1: error: Function is missing a type annotation  [no-untyped-def]
loose.py:5: error: Function is missing a return type annotation  [no-untyped-def]
loose.py:5: error: Function is missing a type annotation for one or more parameters  [no-untyped-def]

Generics in practice

A container should remember what it holds. In modern Python (3.12+) you declare a generic class by putting the type parameter in brackets after the name; the same idea works for functions:

Python
class Stack[T]:
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()


def first[T](items: Iterable[T]) -> T:
    for item in items:
        return item
    raise ValueError("empty")


s = Stack[int]()
s.push(1)
s.push("two")
x = first(["a", "b"])
reveal_type(x)
reveal_type(s.pop())

Iterable comes from collections.abc. mypy catches the second push, and infers that x is a str and s.pop() an int:

TEXT
generic.py:47: error: Argument 1 to "push" of "Stack" has incompatible type "str"; expected "int"  [arg-type]
generic.py:49: note: Revealed type is "str"
generic.py:50: note: Revealed type is "int"

(Older code spells this with T = TypeVar("T") and Generic[T]. It means the same thing.) The type parameters exist only for checking; at runtime a Stack[int] is an ordinary Stack:

Python Generics are erased at runtime

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Protocols in practice

Often you do not care what class an object is, only what it can do. A Protocol describes that shape, and any class with matching methods fits it, with no inheritance (this is structural typing, the static version of duck typing; see Abstract Classes and Protocols).

Python
from typing import Protocol


class SupportsArea(Protocol):
    def area(self) -> float: ...


class Square:
    def __init__(self, side: float) -> None:
        self.side = side

    def area(self) -> float:
        return self.side ** 2


class Circle:
    def __init__(self, r: float) -> None:
        self.r = r

    def perimeter(self) -> float:
        return 6.28 * self.r


def total_area(shapes: list[SupportsArea]) -> float:
    return sum(s.area() for s in shapes)


print(total_area([Square(2)]))
print(total_area([Square(2), Circle(1)]))

Square never mentions SupportsArea, yet it is accepted. Circle has no area() method, so mypy rejects the last line: List item 1 has incompatible type "Circle"; expected "SupportsArea" [list-item]. Protocols are ideal for function parameters: ask for the smallest interface you need rather than a concrete class. Decorate a protocol with @runtime_checkable if you also want isinstance() to work, with the caveat that it only checks that the methods exist, not their signatures.

Python Duck typing and runtime_checkable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last call shows why checking early matters: mypy reports the mistake from the source, while Python only fails when the loop reaches the bad item.

Escape hatches (use sparingly)

Sometimes the checker cannot know what you know. You have three tools, in order of preference:

  • typing.cast(Movie, value) tells the checker "trust me, this is a Movie". It does nothing at runtime, so only use it after you have validated the data yourself.
  • # type: ignore[code] silences one line. Always include the error code (# type: ignore[assignment]) so it silences only what you meant; setting warn_unused_ignores makes mypy tell you when an ignore is no longer needed.
  • Any switches checking off for a value. It spreads: anything computed from an Any is usually Any too.

A common error is Cannot find implementation or library stub for module named "x" [import-not-found]. The package has no hints. Either install its stubs (often a types-<name> package, such as types-requests), or tell mypy to ignore that module only, as shown below.

Configuring mypy

Put settings in pyproject.toml so everyone on the project, and your CI, runs the same checks:

TOML
[tool.mypy]
python_version = "3.14"
strict = true
warn_unused_ignores = true

[[tool.mypy.overrides]]
module = "some_untyped_lib.*"
ignore_missing_imports = true

strict = true switches on a bundle of strict flags: no untyped functions, no implicit Any returns, no unused ignores and more. For a new project start strict. For an existing code base, start with the defaults, fix what it reports, then enable stricter checks per module with overrides until the whole project passes. Run mypy in your editor and in CI next to your tests (see Testing with pytest), and the types become a second safety net.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does mypy do with your program?

    mypy is a static checker. It reads the code and infers types but never executes it, and adds no runtime checks to your program.
  2. 2. Why does name.upper() fail the check when name has type str | None?

    Calling a method on a union must be valid for every member. Narrow the type first, for example with if name is not None:.
  3. 3. What is the key difference between a Protocol and an abstract base class?

    Protocols use structural typing. Any class with compatible methods fits, without inheriting, which is the typed form of duck typing.
  4. 4. Which comment silences only an assignment error on one line?

    A type ignore comment with an error code silences just that kind of error, so other mistakes on the line are still reported.
  5. 5. By default, what does mypy do with a function that has no annotations at all?

    Unannotated functions are not checked by default, which allows gradual adoption. strict mode (or disallow_untyped_defs) makes them errors.

Summary

  • Hints are ignored at runtime; mypy (python -m mypy file.py) checks them statically and reports file:line: error: message [code].
  • Fix arg-type, assignment, attr-defined and union-attr errors by correcting types or narrowing with is not None, isinstance, assert and early returns; reveal_type() shows what mypy infers.
  • Annotate function signatures and let local variables be inferred; unannotated functions are skipped unless you use strict mode.
  • Generic classes and functions (class Stack[T]) keep container types consistent, and Protocols describe the methods you need without inheritance.
  • Prefer cast and # type: ignore[code] over Any, install types-* stubs for untyped libraries, and configure everything in pyproject.toml.

Next: Packaging and Publishing a Library.