Mypy: static typing for Python
Mypy is a static type checker for Python that helps you find bugs before you even run your code. Add type hints to your Python programs, and mypy will warn you when you use those types incorrectly.Python is a dynamic language, so you’ll usually only see errors when you run your code. Mypy is a static checker, so it finds bugs without running them.
input() returns a string, not a number, so adding 1 to it will fail at runtime.
Key features
Gradual typing
Add type hints incrementally to your codebase. Mix typed and untyped code freely.
Powerful type system
Support for generics, callable types, tuple types, union types, structural subtyping, and more.
Non-invasive
Type hints are like comments - your code runs the same with or without them.
Fast incremental checking
Daemon mode provides sub-second incremental type checking for large codebases.
How it works
Type hints don’t interfere with how your program runs. Think of them as enhanced comments:You can always use the Python interpreter to run your code, even if mypy reports errors. Type checking is completely optional.
Gradual typing
Mypy is designed with gradual typing in mind. You can:- Add type hints to your codebase slowly, file by file or function by function
- Always fall back to dynamic typing when static typing isn’t convenient
- Mix typed and untyped code in the same project
- Migrating an existing Python codebase to use static types
- Prototyping new features dynamically, then adding types later
- Working with third-party libraries that don’t have type hints
Type system features
Mypy has a powerful and easy-to-use type system that supports:Type inference
Automatically deduce types from context without requiring annotations everywhere.
Generics
Create reusable code that works with multiple types, like
list[int] or dict[str, float].Callable types
Express function signatures as types, enabling higher-order functions.
Union types
Allow values to be one of several types using
int | str syntax.Tuple types
Fixed-size tuples with per-element types like
tuple[int, str, float].Structural subtyping
Types are compatible based on their structure (protocols), not just inheritance.
Why use mypy?
Using mypy makes your programs:- Easier to understand - Type hints serve as machine-checked documentation
- Easier to debug - Catch type errors before runtime, not during production
- Easier to maintain - Refactor with confidence, knowing the type checker has your back
Getting started
Installation
Install mypy using pip and verify your setup.
Quickstart
Type-check your first Python program in minutes.
Cheat sheet
Quick reference for common type hints and patterns.
Configuration
Configure mypy for your project’s needs.
Compiled with mypyc
Mypy is compiled using mypyc, making it approximately 4x faster than interpreted Python. Mypyc uses Python type hints to compile Python modules to faster C extensions.