Integrating mypy into another Python application
You can integrate mypy into another Python 3 application by importingmypy.api and calling the run function with a list of command line arguments.
Basic integration
Therun function returns a tuple of (normal_report, error_report, exit_status):
The
run function accepts the same arguments that mypy would accept on the command line.Extending mypy using plugins
Python’s dynamic nature and metaprogramming capabilities make it challenging to express all patterns using static types. Mypy’s plugin system lets you customize type checking for libraries that use dynamic APIs.Why use plugins?
Plugins are useful when:- A library uses metaprogramming that’s hard to express with PEP 484 types
- You need to extend mypy’s understanding of third-party framework semantics
- You want to customize type checking behavior for specific patterns
Plugins focus on improving semantic understanding. You cannot define new first-class types.
Configuring mypy to use plugins
Plugins are specified in your mypy configuration file using theplugins option:
- Relative or absolute paths to Python files
- Module names (if installed via pip in the same environment)
Custom entry points
If your plugin uses a different entry point function name:High-level overview
Every plugin entry point function accepts a mypy version string and returns aPlugin subclass:
During semantic analysis and type checking, mypy calls hook methods like
get_type_analyze_hook() on each plugin.Plugin development guidelines
Incremental mode considerations
Plugins can store per-TypeInfo data in the.metadata attribute, which is serialized between runs:
Examples from bundled plugins
Mypy includes several built-in plugins you can reference:- dataclasses - Adds
__init__and other methods to@dataclassdecorated classes - attrs - Supports the attrs library
- ctypes - Handles ctypes array types
- enums - Provides better enum support
Find plugin examples in the mypy/plugins directory.
Testing your plugin
Always test that your plugin handles multiple analysis passes:Forward references in function signatures don’t trigger another pass since functions are processed after the module top level.
Next steps
- Learn about the plugin system hooks and APIs
- Explore additional features for advanced use cases
- Handle runtime troubles with annotations