Start small
If your codebase is large, pick a subset (5,000 to 50,000 lines) and get mypy to run successfully only on this subset first, before adding annotations.Choose a subset
Select a manageable portion of your codebase to start with. This should be doable in a day or two.
Get mypy passing
Fix mypy errors by:
- Inserting annotations requested by mypy
- Adding
# type: ignorecomments to silence errors you don’t want to fix now
Run mypy consistently
Make sure all developers run mypy the same way:Configuration file
Check a mypy configuration file into your codebase:Standardized invocation
Create a script or add to existing tools:Pin mypy version
Ensure everyone runs the same mypy version:Continuous Integration
Add mypy to your CI pipeline as soon as possible:Ignoring errors from certain modules
By default, mypy follows all imports and checks everything. This can result in many errors you don’t want to deal with yet.Ignore specific modules
Use theignore_errors option:
Invert the pattern
For very large codebases, you can ignore everything by default:Per-module configuration
Many options can be configured per-module:Fixing import errors
A common error when starting with mypy:Solutions
Install stub packages
Install stub packages
Many popular packages have stub packages:Search for stubs:
Ignore missing imports
Ignore missing imports
For packages without stubs:
Create your own stubs
Create your own stubs
Create a Then set
.pyi file for the module:MYPYPATH:Incremental adoption strategies
Strategy 1: Bottom-up
Start with modules that have few dependencies:Strategy 2: Top-down
Start with high-level modules:Strategy 3: Feature-based
Annotate by feature or component:- New features: Require full type hints
- Bug fixes: Add type hints to modified code
- Refactoring: Use as opportunity to add types
Dealing with type errors
Quick fixes
- Type: ignore
- Any type
- Cast
Suppress individual errors:
Long-term fixes
- Add proper type annotations
- Refactor code to be more type-friendly
- Use protocols for duck-typed code
- Create stub files for third-party libraries
Measuring progress
Track your progress over time:Tips for success
Be patient
Adopting mypy in a large codebase takes time. Celebrate incremental progress.
Educate the team
Make sure everyone understands the benefits and how to write typed code.
Set policies
Decide on rules: e.g., “all new code must have type hints”
Review together
Use code review to improve type annotations and share knowledge.
The goal isn’t 100% coverage immediately. Even partial type checking provides significant value.