Start small
If your codebase is large, pick a subset of your codebase (say, 5,000to 50,000 lines) and run mypy only on this subset at first,without any annotations. This shouldn’t take more than a day or twoto implement, so you start enjoying benefits soon.
You’ll likely need to fix some mypy errors, either by insertingannotations requested by mypy or by adding # type: ignore
comments to silence errors you don’t want to fix now.
In particular, mypy often generates errors about modules that it can’tfind or that don’t have stub files:
- core/config.py:7: error: Cannot find implementation or library stub for module named 'frobnicate'
- core/model.py:9: error: Cannot find implementation or library stub for module named 'acme'
- ...
This is normal, and you can easily ignore these errors. For example,here we ignore an error about a third-party module frobnicate
thatdoesn’t have stubs using # type: ignore
:
- import frobnicate # type: ignore
- ...
- frobnicate.initialize() # OK (but not checked)
You can also use a mypy configuration file, which is convenient ifthere are a large number of errors to ignore. For example, to disableerrors about importing frobnicate
and acme
everywhere in yourcodebase, use a config like this:
- [mypy-frobnicate.*]
- ignore_missing_imports = True
- [mypy-acme.*]
- ignore_missing_imports = True
You can add multiple sections for different modules that should beignored.
If your config file is named mypy.ini
, this is how you run mypy:
- mypy --config-file mypy.ini mycode/
If you get a large number of errors, you may want to ignore all errorsabout missing imports. This can easily cause problems later on andhide real errors, and it’s only recommended as a last resort.For more details, look here.
Mypy follows imports by default. This can result in a few files passedon the command line causing mypy to process a large number of importedfiles, resulting in lots of errors you don’t want to deal with at themoment. There is a config file option to disable this behavior, butsince this can hide errors, it’s not recommended for most users.