mypy is the reference static type checker for Python, originally created by Jukka Lehtosalo during his PhD at Cambridge and later developed with significant input from Guido van Rossum. It reads your Python source code and type annotations, analyses them without executing the code, and reports type errors — such as passing a str where an int was expected, or accessing an attribute that might not exist.
mypy is configured via pyproject.toml (under [tool.mypy]) or a mypy.ini file. Key settings include strict (enables all optional checks), check_untyped_defs (checks function bodies even without annotations), disallow_any_generics (requires explicit type parameters), and per-module overrides for third-party libraries that lack type stubs. mypy maintains a cache (.mypy_cache/) for incremental checking.
mypy understands Python's full type system: generics, protocols, overloads, type guards, TypeVar bounds, ParamSpec, and more. It can also use stub files (.pyi) that provide type information for libraries written in C or without inline annotations. The typeshed project maintains stubs for the standard library and many popular packages. Alternatives to mypy include pyright (faster, used in VS Code's Pylance) and pytype (Google's type checker with more lenient inference).
Discussed in:
- Chapter 18: Type Hints and Static Analysis — Running mypy