Sub topic 16
Rolling out type checking in an existing codebase
This chapter assumes you can run mypy and Pyright, read their error output, and edit pyproject.toml. It also assumes you know what Any, # type: ignore and strict mode do. The goal is to add checking to a project with thousands of unannotated lines without a freeze on feature work, and without a first run that reports 4,000 errors.
Why a big-bang rollout fails
Running a checker in strict mode on an untyped codebase produces a wall of errors. Nobody can review that, and a single pull request that fixes them all will conflict with every other open branch. Teams that try it usually either abandon the effort or silence everything with blanket ignores, which leaves checking turned on but useless.
Gradual typing lets you avoid this. Unannotated code is treated as Any, so you can check a small area strictly and leave the rest alone. A rollout then has three jobs:
- Get a passing, non-strict run into CI.
- Stop the error count from growing.
- Raise strictness one module at a time.
Stage 1: Get a passing baseline
Start with the most permissive configuration that still runs. Check only the package directory, pin the Python version, and exclude code you do not intend to touch soon.
[tool.mypy]
python_version = "3.12"
files = ["src"]
warn_unused_ignores = true
[[tool.mypy.overrides]]
module = ["myapp.legacy.*"]
ignore_errors = true
[tool.pyright]
pythonVersion = "3.12"
include = ["src"]
typeCheckingMode = "basic"
ignore = ["src/myapp/legacy"]The two tools handle excluded code differently:
- mypy's
ignore_errors = truestill analyzes the module, because other modules import its types. It only hides the errors. - Pyright's
ignoredoes the same thing. Itsexcludesetting is different: it removes files from the analysis roots entirely.
Prefer ignore over exclude for code that other modules import. Otherwise you lose type information at the boundary.
Run the checker and sort what you see into three groups:
- Missing stubs or untyped imports. Install stub packages such as
types-requests, or add a per-module override for libraries with no types. - Genuine bugs. Fix these first, because they are the quickest evidence that the work is worth doing.
- Annotation problems. These are real mismatches, such as a function that returns
str | Nonebut is used asstr. Fix the small ones. Suppress the rest with a targeted ignore that carries an error code (# type: ignore[arg-type]), so each one can be found and removed later.
Turn on warn_unused_ignores from the start. When a later fix makes an ignore unnecessary, the checker reports it, so the ignores do not pile up.
Stage 2: Stop new errors from landing
A passing run is not enough if someone can add an error tomorrow. Put the checker in CI so the build fails on any error in the current configuration. If the baseline cannot reach zero yet, use a ratchet: record the current error count and fail whenever it goes up.
import subprocess
import sys
from pathlib import Path
BASELINE = Path("mypy-baseline.txt")
def count_errors() -> int:
result = subprocess.run(
[sys.executable, "-m", "mypy", "src/"],
capture_output=True,
text=True,
)
return sum(1 for line in result.stdout.splitlines() if ": error:" in line)
def main() -> int:
current = count_errors()
allowed = int(BASELINE.read_text().strip())
if current > allowed:
print(f"Type errors increased: {current} > {allowed}")
return 1
if current < allowed:
print(f"Errors fell to {current}. Write {current} to {BASELINE} to lock it in.")
return 0
if __name__ == "__main__":
sys.exit(main())A count has a weakness. A pull request that fixes one error and adds another leaves the number unchanged and passes. If that matters, store the list of existing errors, normalized without line numbers, and fail on any entry that is not in the stored list. The third-party mypy-baseline package does this for mypy. A plain count is a good enough start for most teams.
Stage 3: Check the bodies of untyped functions
This step catches teams out. By default, mypy skips the body of a function that has no annotations. It does not report errors inside it, and it treats the function's parameters as Any. A project can pass mypy while a large share of its code is never examined. Pyright behaves differently: it infers types in unannotated functions and checks them, so the same code can produce many more errors under Pyright than under mypy.
Enable the check in mypy:
[tool.mypy]
check_untyped_defs = trueThis usually produces a new batch of errors, mostly real ones such as attribute access on None or calls with the wrong number of arguments. It does not require you to write any annotations, so it is a cheap way to gain coverage. Expect to spend a few days fixing this batch on a mid-sized project, and do it before asking people to annotate functions.
Stage 4: Strict mode per module
Strict mode on the whole project is the end state. On the way there, apply it only to modules that are ready: new code, small leaf modules, and anything with high business risk such as billing or authentication.
In pyproject.toml, mypy uses per-module overrides and Pyright uses a list of strict paths:
[[tool.mypy.overrides]]
module = ["myapp.billing.*", "myapp.core.*"]
disallow_untyped_defs = true
disallow_any_generics = true
warn_return_any = true
no_implicit_optional = true
[tool.pyright]
strict = ["src/myapp/billing", "src/myapp/core"]You can also opt a single file in with a comment at the top. This is useful for new files in an otherwise lax package:
# mypy: disallow-untyped-defs, disallow-any-generics
# pyright: strict
def total(prices: list[float]) -> float:
return sum(prices)When strict code imports lax code, the lax code's functions return Any, which weakens the checking at that boundary. Work from the leaves inward: type the modules that others import first, then the modules that import them.
Stage 5: Widen the strict set
Treat the strict list as a to-do list that only grows. Common ways to pick the next module:
- New code rule. Every new file must pass strict mode, whatever the rest of the project does.
- Touch rule. When a developer changes a lax module for any reason, they annotate the functions they touched and, if the module is then clean, add it to the strict list.
- Dependency order. Choose modules with the most importers, since typing them improves checking everywhere else.
Tools that generate annotations from runtime traces, such as MonkeyType, can speed up the first pass. Treat their output as a draft. Traces record only the types seen in the sample runs, so they tend to produce overly narrow types, and a human must review them.
Common failure modes
| Problem | Cause | Fix |
|---|---|---|
| Passing checks but bugs still reach production | `check_untyped_defs` is off, so bodies are skipped | Enable it in stage 3 |
| Strict module reports `Any` leaks from a lax import | The imported function has no annotations | Annotate the import first, or wrap it with an annotated adapter |
| Ignores keep growing | Bare `# type: ignore` with no code | Require error codes and `warn_unused_ignores` |
| Developers see different results from CI | Different tool versions | Pin mypy and Pyright versions in a requirements file |
| Large first run blocks the team | Strict mode enabled globally | Start with stage 1 settings and ratchet |
Exercise
A project passes mypy with its default settings, yet a function with no annotations contains the line user.name.upper() where user can be None. Why does mypy not report it, and which setting changes that?
Show answer
By default mypy does not check the body of a function that has no annotations, and it treats the parameters as Any. The setting check_untyped_defs = true makes mypy check the body, and it would then report the access on None. Pyright reports the error without extra settings, because it infers types inside unannotated functions.
Exercise
Your team has a ratchet that fails when the error count rises. One pull request fixes two errors and introduces two new ones. Does the ratchet fail the build, and what change would catch it?
Show answer
It does not fail, because the count is unchanged. Storing the list of known errors, without line numbers, and failing on any error not in that list would catch it. The mypy-baseline package implements this approach.