mypy --strict is the maximalist setting: every function must be typed, every untyped expression flagged, no implicit Any. The payoff is that the type system catches real bugs at PR review, not at 3 AM on Saturday. The cost is that turning it on for an untyped codebase yields 2000 errors on day one. This article shows the gradual-enablement pattern that gets a real production codebase to strict without a flag day, plus the CI rules that keep it strict afterwards.
How to verify
Check the current state and what would change under strict:
mypy --version
mypy --strict app/ tests/ 2>&1 | tail -20
mypy --strict app/ tests/ 2>&1 | grep -c "error:"
cat mypy.ini pyproject.toml 2>/dev/null | grep -A 20 "\[mypy"
find . -name "*.py" | xargs grep -l "from typing import Any" | head
If the strict error count is over 500, don’t try to fix all at once — see step 2.
What’s happening
mypy infers types from annotations and the standard library’s type stubs. --strict is a meta-flag that turns on every individual stringency option: disallow-untyped-defs, disallow-any-generics, warn-return-any, warn-unused-ignores, and others. Each one independently catches a category of issue — an untyped function, a List without a parameter, a function returning Any, an # type: ignore that no longer applies.
The gradual approach is built into mypy via per-module overrides. You can mark module = "app.new.*" as strict and leave module = "app.legacy.*" with the looser default. Over time, you migrate modules from loose to strict, and the override list shrinks until it’s empty.
The third-party-stubs question is the other practical hurdle. Many PyPI packages ship py.typed and have inline annotations. Many don’t, in which case you need a separate stubs package (types-requests, django-stubs, types-PyYAML) or you put # type: ignore[import] at the call site. The right reflex is: install stubs first, ignore only as a last resort.
The procedure
-
Set up
pyproject.tomlwith strict as the global default and loose overrides per module:[tool.mypy] python_version = "3.12" strict = true warn_unused_ignores = true warn_redundant_casts = true show_error_codes = true plugins = ["pydantic.mypy"] [[tool.mypy.overrides]] module = "app.legacy.*" strict = false ignore_errors = true # silenced entirely [[tool.mypy.overrides]] module = "app.partially_typed.*" disallow_untyped_defs = false # allow untyped defs, but other strict on -
Discover the per-module error baseline:
mypy --strict app/ 2>&1 \ | awk -F: '/error:/ {print $1}' \ | sed 's|/[^/]*\.py$||' \ | sort | uniq -c | sort -rn | head -20This shows the top 20 directories by error count. The ones at the top are your “loose now, migrate later” candidates — silence them in the overrides block and start strict everywhere else.
-
Install the third-party stubs you need.
mypy --install-typesdoes it interactively, but for CI use explicit deps:pip install \ django-stubs[compatible-mypy] \ types-requests \ types-PyYAML \ types-redisAdd these to
requirements-dev.txtso CI sees them. -
Configure
[tool.django-stubs]if Django:[tool.django-stubs] django_settings_module = "project.settings"This lets the Django plugin understand
Manager-typed queries. -
Wire to CI as a gate:
- name: mypy run: | pip install -r requirements-dev.txt mypy --strict --pretty app/ tests/--prettyshows the offending source line, not just file:line:col — helpful in PR comments. -
To make migration tractable, write a one-time
# type: ignore[<code>]sweep tool. For each error in a “needs migration” module, append# type: ignore[error-code] # TODO: typeto the line:mypy --strict app/old/ --no-error-summary 2>&1 | \ while IFS=: read -r file line col rest; do code=$(echo "$rest" | grep -oP '\[\K[^\]]+' | head -1) [ -n "$code" ] && sed -i "${line}s|$| # type: ignore[$code] # TODO: type|" "$file" doneNow the module is “passing” but every silenced location is searchable. Strip the comments one module at a time.
-
Pre-commit hook so mypy runs on changed files only (faster than full repo):
# .pre-commit-config.yaml - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.10.0 hooks: - id: mypy additional_dependencies: - django-stubs[compatible-mypy] - types-requests
Common pitfalls
- Adding
# type: ignorewithout an error code —# type: ignore[no-untyped-def]is reviewable; bare# type: ignorehides every error on that line, including ones added later. Withwarn_unused_ignores = true, bare ignores eventually flag themselves. - Adding
from typing import Anyeverywhere —Anyopts out of type checking. If you’re typing legacy code, preferobject(the “I don’t know but I won’t access it”) overAny(the “type checker, please look away”). - Forgetting the
pydantic.mypyplugin — Pydantic models without it appear to mypy as “any field on this class is unknown.” With the plugin, mypy reads the model definition. - Running mypy without
--no-implicit-reexportand exporting from__init__.py— submodules withfrom .foo import Barthen re-export silently.--strictenables this. - Different mypy versions in dev vs CI — output and error codes shift between minor versions. Pin
mypy==1.10.0inrequirements-dev.txt.
For the lint-and-format side of the same pipeline, see Black and Ruff formatting pipeline. Stack Harbor’s managed operations practice enables mypy --strict from day one on new client projects and uses the per-module override pattern for inherited codebases — the type-error catch rate at PR review consistently exceeds the cost of writing the annotations.