Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 38 ยท Linting, Types and Formatting

Type Checking with mypy

Find bugs before running code with Python type hints and mypy. Run mypy for real, learn strict mode, Optional narrowing, config in pyproject.toml and py.typed.

Python is dynamically typed: a function that expects a number will happily accept a string until the day it crashes in production. Type hints let you describe what you expect, and a type checker such as mypy reads those hints and reports mismatches before the program runs. The hints are optional and ignored at runtime, so you can add them gradually.

This lesson shows type checking running for real, covers the situations that surprise newcomers (None, untyped code, strict mode) and explains how to configure mypy and ship type information with your package.

Your first type errors

Hints are written after a colon for parameters and after -> for return values. Run mypy on a small module to see it work:

Python Run mypy on a small module

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.

Each message has a line number, a description and an error code in brackets such as [arg-type], [assignment] or [return-value]. The exit status is non-zero when errors are found, which is what lets CI fail a build.

The runner's mypy loads in a browser, so the first run is slow while the large type library is read. On your own computer, mypy src/ is quick, and its cache (.mypy_cache) makes later runs faster.

Optional and None

The most common real bug in Python is calling a method on None. A hint such as str | None (or Optional[str]) says "might be missing", and the checker forces you to handle it:

Python Narrowing None

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.

After if other is not None:, mypy knows the type is plain str inside the block. This is called type narrowing, and it works with isinstance(), truthiness tests, early returns and assert. reveal_type() is a debugging helper that makes mypy print what it inferred; remove it before running the real program, because it only exists for the checker.

Gradual typing and strict mode

By default mypy is lenient. It skips the body of functions that have no annotations at all, so untyped code gets no checking. That allows gradual adoption, but it also means you may get a false sense of safety. The --strict flag turns on a bundle of stricter checks:

Python Default mode versus strict mode

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.

Strict mode reports missing annotations (no-untyped-def), bare generics such as list (write list[int]), and more. A practical adoption path:

  1. Start with default mode and fix what it finds.
  2. Turn on strictness per module for new code, using overrides.
  3. Raise the bar over time until you can enable strict = true everywhere.

Configuring mypy

Put the settings in pyproject.toml:

TOML
[tool.mypy]
python_version = "3.11"
strict = true
warn_unreachable = true
files = ["src", "tests"]

# Relax rules for code you have not typed yet
[[tool.mypy.overrides]]
module = "myapp.legacy.*"
disallow_untyped_defs = false

# Third-party packages without type information
[[tool.mypy.overrides]]
module = ["somelib.*"]
ignore_missing_imports = true
  • files tells mypy (with no arguments) what to check.
  • overrides apply different rules to selected modules, which is how large code bases migrate step by step.
  • ignore_missing_imports silences errors for libraries that ship no type hints. Prefer installing a stub package (such as types-requests) when one exists.

Silence a single line with # type: ignore[code], and add warn_unused_ignores = true (part of strict) so stale ignores are reported.

Typing your package for others

If you publish a library, your users' type checkers can use your hints, but only if you tell them to. Two ingredients make a package typed:

  1. Your code has annotations.
  2. An empty marker file named py.typed sits inside the package directory, and your build includes it in the wheel (most backends do this automatically for files inside the package, but check).
TEXT
src/
  myapp/
    __init__.py
    core.py
    py.typed        <- empty file; says "this package ships its own types" (PEP 561)

Without py.typed, mypy treats your package as untyped and falls back to Any for everything imported from it. You can verify the result by running mypy on a small script that imports your installed package and checking reveal_type.

Other checkers

mypy is the reference implementation, but not the only one. Pyright (used by the Pylance editor extension) is fast and strict. ty and pyrefly are newer checkers written in Rust. They all read the same hints, so the work you put into annotations is portable. Many projects run one checker in CI and let the editor use another.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When do Python type hints affect how your program runs?

    Annotations are stored but not enforced by Python itself. A tool like mypy analyzes them separately.
  2. 2. def f() -> str | None: returns a value you call .upper() on. What does mypy do?

    Calling a method on a possibly-None value is an error; after if value is not None: the type is narrowed to str.
  3. 3. What does mypy do with the body of a function that has no annotations, in default mode?

    Untyped functions are not checked by default, which allows gradual typing. --strict and check_untyped_defs change that.
  4. 4. What marks a package as shipping its own type hints?

    PEP 561 defines the py.typed marker; include it in your wheel so users' checkers trust your annotations.

Summary

  • Type hints describe expectations; mypy checks them statically and exits non-zero on errors.
  • X | None forces handling of missing values, and checks such as is not None narrow the type.
  • Default mode skips untyped functions; strict = true and per-module overrides let you tighten gradually.
  • Configure mypy in [tool.mypy]; use stub packages or ignore_missing_imports for untyped dependencies.
  • Ship an empty py.typed file so users benefit from your hints.

Next: pre-commit Hooks