In this lesson, you will learn how to generate and interpret type coverage reports to systematically identify and address untyped segments of your codebase.
While running mypy tells you where your code is currently broken, it doesn't give you a high-level view of how much of your project is actually "type-safe." As your application grows, you need a way to track your progress and decide where to focus your refactoring efforts.
Generating the Report
To move beyond simple error output, you can use the mypy --html-report flag. By running:
mypy --html-report report_directory my_package/
Mypy will generate a series of HTML files inside the specified directory. When you open index.html in your browser, you will see a detailed dashboard. This report color-codes your files based on their "type coverage" percentage—the ratio of typed lines versus untyped lines.
Analyzing the Data
Don't aim for 100% coverage immediately; it’s rarely practical for large legacy codebases. Instead, use the report to prioritize your work:
- Identify "Low-Hanging Fruit": Look for modules that are nearly fully typed. It is often very easy to add type hints to a file that is already at 90% coverage to push it to 100%.
- Focus on Critical Paths: Prioritize core logic or shared utility modules. If a high-traffic utility function is flagged as "untyped" (appearing as
Any), it risks propagating type errors throughout your application. - Decompose Large Untyped Files: If a large file has low coverage, use the report to track your incremental improvements. By refactoring just one class or function at a time, you can see your percentage increase in the report, providing a sense of momentum.
By visualizing where your type-safety gaps exist, you transform type hinting from a reactive "fix the error" process into a proactive "code quality improvement" strategy.
Key Takeaway: Use HTML type coverage reports to visualize your progress and strategically prioritize refactoring by targeting critical modules with low type density.