Sub topic 18
Adding type hints to an existing codebase
This chapter assumes you can write annotations, run mypy or pyright, and narrow X | None values. It covers how to add hints to code that has none, without stopping the team's work.
Why gradual adoption works
Python's type system is gradual. A function with no annotations is treated as if its parameters and return value were Any, and a checker skips most checks inside it. You can annotate one function, one module, or one package at a time, and the rest of the code keeps passing.
Start with a lenient configuration
Install a checker and run it on the whole project. Expect many errors on the first run. Record the current state in a config file so the team starts from a clean, passing build. This example uses mypy in pyproject.toml:
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
check_untyped_defs = false
[[tool.mypy.overrides]]
module = "legacy.*"
ignore_errors = trueThe overrides section silences a whole package that you are not ready to touch. Shrink that list over time.
Choose what to annotate first
Annotate the code that many other files use, because each hint there improves checking in every caller.
- Shared helpers and utility modules.
- Public functions at package boundaries.
- Data shapes that travel between modules. Use dataclasses or
TypedDictfor these. - New code, which you annotate from the first commit.
Code that changes often or is about to be rewritten can wait.
Use Any as a temporary marker
When a type is unclear, Any lets the checker move on. Use it deliberately, and leave a comment so it can be found later.
from typing import Any
def load_config(path: str) -> dict[str, Any]:
# TODO: replace Any with a TypedDict once the keys are stable
import json
with open(path) as f:
return json.load(f)
settings = load_config("settings.json")
print(settings.get("debug", False))Prefer object when you only need to accept any value and will not use it, because the checker then forces you to narrow it first.
Tighten step by step
After a module is annotated, turn on stricter checks for that module only. Mypy allows per-module overrides.
[[tool.mypy.overrides]]
module = "billing.*"
disallow_untyped_defs = true
warn_return_any = trueOnce every module is covered, move the strict options to the global section and delete the overrides.
Common errors
- Annotating everything with
Anyto silence errors. The checker passes but finds nothing. Search forAnyregularly. - Scattering
# type: ignorecomments. Use# type: ignore[code]with the specific error code, and enablewarn_unused_ignoresso stale ones are reported. - Treating a hint as a runtime check. If untrusted input needs validation, validate it explicitly. Hints do not do it.
- Big-bang rewrites. A single large pull request that annotates everything is hard to review. Prefer small changes, one module each.
Exercise
Your project has 200 untyped modules and mypy reports 1,500 errors. Describe a plan that gets CI passing today and still makes progress.
Show answer
Add a lenient mypy config, use per-module overrides with ignoreerrors for modules that fail, and commit it so the build passes. Enable the checker in CI. Then annotate shared, stable modules first, removing each module from the ignore list as it passes. Finally enable stricter options such as disallowuntyped_defs per module, and move them to the global section when all modules are covered.