Pytest Mypy Plugin
pytest-mypy is a pytest plugin that integrates the Mypy static type checker into your pytest test runs. It allows you to run Mypy checks on your Python source files as part of your existing test suite, similar to how pytest-flake8 works for Flake8. The current version is 1.0.1, and it is actively maintained, with releases as needed.
Warnings
- gotcha Mypy configuration flags like `--ignore-missing-imports` or not using strict checking (`--strict`, `--disallow-untyped-defs`) can cause Mypy to silently miss type errors. Users might mistakenly believe their code is fully type-checked when issues are being suppressed.
- gotcha When Mypy is run as a subprocess (the default behavior of `pytest-mypy`), relative paths specified in environment variables like `MYPYPATH` or `PYTHONPATH` may not resolve correctly because pytest tests can run in temporary working directories.
- gotcha By default, Mypy does not fully check functions without type annotations, and `Any` types can propagate through your code, masking potential type errors. This can lead to false negatives in your type checking results.
Install
-
pip install pytest-mypy
Imports
- pytest-mypy
This is a pytest plugin and is automatically discovered upon installation; no explicit import statement is typically needed in your test files.
Quickstart
# my_project/my_module.py
def add_numbers(a: int, b: int) -> int:
return a + b
def incorrect_call():
# Mypy should flag this type mismatch
return add_numbers('hello', 5)
# my_project/test_example.py (empty or with other tests)
# This file just needs to exist for pytest to discover the project.
# To run mypy with pytest (from my_project directory):
# pip install pytest pytest-mypy mypy
# pytest --mypy my_module.py
# Example conftest.py to add extra mypy arguments (e.g., --strict):
# # my_project/conftest.py
# def pytest_configure(config):
# plugin = config.pluginmanager.getplugin('mypy')
# if plugin:
# # Example: make mypy run in strict mode
# plugin.mypy_argv.append('--strict')
# # Example: check untyped definitions
# plugin.mypy_argv.append('--disallow-untyped-defs')