Sub topic 18
Adding type hints to an existing codebase
This chapter assumes you can annotate functions, run mypy or pyright, and use X | None, Any, object, and TypedDict. It covers how to add hints to code that has none, without a rewrite and without thousands of errors on day one.
Why gradual adoption works
Python typing is gradual. Code without annotations is treated as Any, and Any is compatible with every type. You can therefore annotate one function, one module, or one package at a time, and the checker only enforces what you have declared.
Two defaults surprise people:
- mypy skips the body of a function that has no annotations at all. An obvious bug inside it goes unreported.
- pyright infers types from the body of unannotated functions and checks them, so it reports more on the same code.
Because of this, "zero errors" on an untyped codebase says little. Adoption means widening what the checker is allowed to look at.
def shout(text):
return text.upper().nonexistent() # mypy: not checked
def shout_typed(text: str) -> str:
return text.upper().nonexistent() # mypy: "str" has no attribute "nonexistent"Setting check_untyped_defs = true in mypy makes it check the first function too. It is a cheap first step because it requires no new annotations.
A phased plan
- Baseline. Run the checker once and record the result. Do not fix everything yet. Fixing 2,000 errors in one pull request is unreviewable.
- New code first. Require annotations on every new function. This stops the problem from growing.
- Boundaries and public APIs. Annotate the functions other modules call, and the places where data enters: HTTP handlers, file parsers, database rows. Interior helpers can wait, because their types are often inferred from the boundary.
- Per-module strictness. Raise the rules for packages that are finished.
- Ratchet. Fail CI if the error count rises. Lower the allowed count as you fix things.
Configure per-module strictness
Keep one global config that is lenient, then tighten selected packages. mypy supports this in pyproject.toml:
[tool.mypy]
python_version = "3.12"
check_untyped_defs = true
warn_unused_ignores = true
warn_redundant_casts = true
[[tool.mypy.overrides]]
module = ["billing.*", "api.*"]
disallow_untyped_defs = true
disallow_any_generics = true
warn_return_any = true
[[tool.mypy.overrides]]
module = ["legacy.*"]
ignore_errors = true| Setting | Effect | Use it when |
|---|---|---|
| `check_untyped_defs` | Checks bodies of unannotated functions | Always, from the start |
| `disallow_untyped_defs` | Errors on any function missing annotations | A package is fully annotated |
| `disallow_any_generics` | Rejects bare `list` or `dict` | You want `list[int]`, not `list[Any]` |
| `warn_return_any` | Flags returning `Any` from a typed function | You want to find leaks of `Any` |
| `warn_unused_ignores` | Reports `# type: ignore` comments that are no longer needed | Always, so ignores do not rot |
| `ignore_errors` | Silences a module entirely | Parking code you will not touch yet |
Pyright offers the same idea. Set typeCheckingMode to "basic" globally and list finished packages under strict in [tool.pyright].
Annotate from the boundary inward
Take an untyped function that processes dictionaries:
def total_price(items, tax):
return sum(i["price"] for i in items) * (1 + tax)Every argument is Any, so any caller can pass anything. Start by describing the data shape, because that fixes the types of everything that touches it:
from typing import TypedDict
class Item(TypedDict):
name: str
price: float
def total_price(items: list[Item], tax: float) -> float:
return sum(i["price"] for i in items) * (1 + tax)
print(total_price([{"name": "pen", "price": 2.0}], 0.2))A checker now flags i["prise"] and flags callers that pass strings for tax. Callers that are still unannotated are not flagged, because their arguments are Any. That is why the annotations pay off more as coverage grows.
Handling data you cannot type yet
json.loads returns Any. If you pass it straight through, Any spreads into every variable it touches, and the checker quietly stops helping. Convert it to object and narrow it at the boundary:
import json
def load_count(raw: str) -> int:
data: object = json.loads(raw)
if isinstance(data, dict) and isinstance(data.get("count"), int):
return data["count"]
raise ValueError("missing integer 'count'")
print(load_count('{"count": 3}'))This costs a few lines. It turns a runtime KeyError or a wrong-typed value somewhere downstream into a clear error at the edge.
Escape hatches and their cost
Sometimes the checker is wrong, or the code is too dynamic to describe. You have two tools.
# type: ignore[code] suppresses one error on one line. Always include the error code, so the comment hides only the error you meant to hide, and add a reason:
import legacy_helpers # type: ignore[import-not-found] # no stubs, tracked in #412cast tells the checker to trust you, and it does no checking at runtime:
from typing import Any, cast
raw: dict[str, Any] = {"count": "three"}
count = cast(int, raw["count"])
print(count + 1) # the checker is satisfied, but this raises TypeErrorTurn on warn_unused_ignores and warn_redundant_casts. They report escape hatches that are no longer needed, so the count shrinks as the code improves.
Third-party libraries
An untyped import is treated as Any, which hides errors. Resolve it in this order:
- Check whether the library ships its own types. Many do, through a
py.typedmarker. - Install a stub package such as
types-requestsortypes-PyYAML. - Add a per-module override with
ignore_missing_imports = truefor that one library.
Avoid setting ignore_missing_imports globally. It also hides typos in import names.
Common failure modes
- Annotating with
Anyto make errors disappear. The error count drops while the real coverage does not. Usewarn_return_anyand review newAnyin code review. - Bare containers.
def f(x: list)meanslist[Any]. Usedisallow_any_genericsin finished packages. - Fixing
Noneerrors with# type: ignore. Astr | Noneerror often points to a real bug. Narrow withif x is not None. - Annotating a function that returns
Noneimplicitly on some paths. The checker reports "missing return statement". Fix the control flow, not the hint. - Mutable defaults.
def f(x: list[int] = [])type checks but shares one list across calls. A checker will not catch this, so useNoneand create the list inside. - Unannotated callers. A fully typed function gives no protection when every caller passes
Any. Check coverage on the callers too.
Exercise
Your mypy run on a legacy package reports zero errors, but you know the package has bugs. Name the likely cause and the first setting you would change.
Show answer
Most functions in the package have no annotations, and mypy does not check the bodies of unannotated functions by default. Set check_untyped_defs = true so mypy checks those bodies. Expect new errors to appear, and handle them with the baseline and ratchet approach rather than fixing them all at once.
Exercise
A function parses a JSON config and returns data["port"] with the return type int. The checker accepts it because json.loads returns Any. Rewrite the check so a missing or non-integer port fails with a clear error.
Show answer
Assign the result to data: object, then test isinstance(data, dict) and isinstance(data.get("port"), int). Return data["port"] inside the if, and otherwise raise ValueError("missing integer 'port'"). This narrows the value at the boundary instead of letting Any spread.