Specifying code to be checked
Mypy provides several ways to specify which files to type check:- Files and directories
- Module names
- Package names
- Code strings
Pass paths to Python files and directories directly:Mypy will recursively type check the entire contents of any provided directories.
Multiple targets
You can specify multiple packages and modules on the command line:Reading from a file
You can read additional command-line arguments from a file using the@ prefix:
mypy $(cat file_of_files.txt).
Using configuration files
You can use thefiles option in your mypy.ini file to specify which files to check, then simply run mypy with no arguments.
How mypy finds imports
Module discovery
Mypy uses an algorithm similar to Python’s import system to locate modules:Mypy resolves imports relative to the current working directory by default.
Mapping file paths to modules
When you pass file paths to mypy, it maps them to module names:Following imports
By default, mypy follows all imports and type checks imported modules:Control import following
Control import following
Use
follow_imports configuration to control this behavior:normal- Follow imports and type check (default)silent- Follow imports but suppress errorsskip- Don’t follow imports at allerror- Treat imports as errors
Common import issues
Cannot find module
If mypy reports it cannot find a module:- Check the module is installed in the environment where you run mypy
- Install stub packages for third-party libraries (e.g.,
types-requests) - Use
ignore_missing_imports = Truefor modules you can’t type check - Set
MYPYPATHto include custom stub directories
Namespace packages
For namespace packages without__init__.py:
Best practices
Use configuration files
Store mypy settings in
mypy.ini or pyproject.toml for consistency across your team.Pin mypy version
Pin mypy version in your requirements to ensure consistent behavior in CI.
Run in CI
Add mypy to your continuous integration pipeline to catch type errors early.
Use incremental mode
Enable incremental mode for faster repeated checks on large codebases.
Performance tips
For large projects:- Use
--cache-dirto specify a cache location - Enable incremental mode (on by default)
- Consider using remote caching for CI environments
- Use
--skip-version-checkif you’re certain dependencies haven’t changed