Python

Taking a Real Codebase to mypy --strict

Turning on mypy --strict in a real codebase does not produce one error list. It produces a sequence: the import fails first, then the missing annotations, then the Any values that strict mode lets through, then the ignore comments and the shape decisions. This guide migrates one real script — the spacing checker this site runs against its own pages — through that sequence, in the order the errors actually block, with every diagnostic quoted from the run that produced it.

Written November 6, 2026 · Tested with Python 3.12.3 · 18 min read

By the end of this guide
  • Step 0: the first run, and the interpreter surprise
  • Step 1: annotate every definition
  • Step 2: the Any that --strict lets through
  • Step 3: TypedDict at the JavaScript boundary

Edited November 18, 2026

What you will build

The migration target is check_spacing.py, a 191-line script from this site's own repository. It serves the built site over local HTTP, drives headless Chromium through Playwright, runs a JavaScript snippet in every page to measure the gaps around h2 headings and sections, and prints the pages where headings are crowded. It is real, it is in daily use, and before this migration it had no type annotations at all: five function definitions, three classes, and no annotation anywhere.

The toolchain is Python 3.12.3 with mypy 2.4.0 (compiled) on Ubuntu 24.04, Playwright 1.42.0, and headless Chromium. The migration floor is Python 3.12, because the last step converts a generic container to the PEP 695 syntax, which needs 3.12. Nothing here was tested with pyright, and nothing was tested with MSVC or any other Python version.

The order below is the order the errors blocked, not the order a tutorial would teach the features. Each step ends with the exact mypy --strict output for that state of the file, including the steps where the output is empty and the file is still wrong.

Step 0: the first run, and the interpreter surprise

The first command is the plain one:

Terminal
$ mypy --strict --show-error-codes check_spacing.py
check_spacing.py:11: error: Cannot find implementation or library stub for module named "playwright.sync_api"  [import-not-found]
check_spacing.py:11: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
check_spacing.py:17: error: Function is missing a type annotation  [no-untyped-def]
check_spacing.py:20: error: Function is missing a type annotation  [no-untyped-def]
check_spacing.py:27: error: Function is missing a return type annotation  [no-untyped-def]
check_spacing.py:37: error: Function is missing a return type annotation  [no-untyped-def]
check_spacing.py:171: error: Function is missing a return type annotation  [no-untyped-def]
check_spacing.py:171: note: Use "-> None" if function does not return a value
check_spacing.py:173: error: Call to untyped function "check_spacing" in typed context  [no-untyped-call]
check_spacing.py:191: error: Call to untyped function "main" in typed context  [no-untyped-call]
Found 8 errors in 1 file (checked 1 source file)

The first error is the one to fix first, and it is not about the code. Playwright is installed — python3 -c "import playwright" works, and the package ships its own py.typed marker, so no stubs are missing. The compiled mypy binary simply does not resolve it from its default interpreter search. Pointing mypy at the system interpreter resolves the import with nothing else changed:

Terminal
$ mypy --strict --show-error-codes --python-executable /usr/bin/python3 check_spacing.py
Found 7 errors in 1 file (checked 1 source file)

The same seven annotation errors remain; only the import error is gone. The fix belongs in a mypy.ini so nobody has to remember the flag:

INI
[mypy]
strict = True
show_error_codes = True
python_executable = /usr/bin/python3

Two things about --strict itself are worth pinning down before going further. First, the exact flag list changes between mypy versions — the mypy command-line documentation says so, and the installed mypy 2.4.0 confirms it. Its --help lists the strict bundle as --disallow-any-generics, --disallow-subclassing-any, --disallow-untyped-calls, --disallow-untyped-defs, --disallow-incomplete-defs, --check-untyped-defs, --disallow-untyped-decorators, --warn-redundant-casts, --warn-unused-ignores, --warn-return-any, --no-implicit-reexport, --strict-equality, and --extra-checks. That list matches the current documentation for mypy 2.4.1 exactly. Second, --warn-unreachable is not in the bundle, so strict mode does not warn about dead code.

Step 1: annotate every definition

The seven remaining errors are all one class: functions without annotations, and calls to those functions from typed code. The fix is mechanical — annotate every definition, including the two methods on the request handler and the *args/**kwargs passthrough, which take Any:

Python
from collections.abc import Iterator
from typing import Any

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, directory=str(DIST_DIR), **kwargs)

    def log_message(self, format: str, *args: Any) -> None:
        pass

@contextmanager
def serve_dist() -> Iterator[int]:
    with ReusableTCPServer(("", 0), Handler) as httpd:
        port = httpd.server_address[1]
        server_thread = Thread(target=httpd.serve_forever, daemon=True)
        server_thread.start()
        try:
            yield port
        finally:
            httpd.shutdown()

def check_spacing() -> list[dict[str, Any]]:
    results: list[dict[str, Any]] = []
    # ... unchanged body ...
    return results

def main() -> None:
    # ... unchanged body ...

Run it:

Terminal
$ mypy --strict --show-error-codes check_spacing.py
Success: no issues found in 1 source file

This is the first trap in the migration, and it is the reason the order matters. The file passes --strict and is still untyped in every way that counts: check_spacing returns list[dict[str, Any]], every value coming back from the browser is Any, and every dictionary access in main is unchecked. Strict mode checks annotations; it does not check that your annotations mean anything. The --disallow-any-expr flag would catch Any expressions, but it is not part of --strict, and turning it on for a whole codebase at once is a different migration. So the annotation pass is step one because nothing else is visible until the definitions are annotated — mypy cannot check a function body it has not been told the types of — and the Any elimination is a separate, deliberate step two.

Step 2: the Any that --strict lets through

Three small probes show where Any leaks and which strict flags catch it. Each probe was run against the installed mypy 2.4.0:

Python
def bare_generic() -> list:
    return [1, 2, 3]

def return_any(value: Any) -> list[int]:
    return value

def empty_list() -> list[int]:
    results = []
    return results
Terminal
$ mypy --strict --show-error-codes probe-any.py
probe-any.py:11: error: Missing type arguments for generic type "list"  [type-arg]
probe-any.py:22: error: Returning Any from function declared to return "list[int]"  [no-any-return]
Found 2 errors in 1 file (checked 1 source file)
Terminal
$ mypy --strict --show-error-codes probe-any2.py
probe-any2.py:5: error: Need type annotation for "results" (hint: "results: list[<type>] = ...")  [var-annotated]
Found 1 error in 1 file (checked 1 source file)

The three errors are the three ways Any enters through a typed signature: a bare generic (list with no parameter, caught by --disallow-any-generics), an Any value returned from a function that promises a concrete type (caught by --warn-return-any), and an empty collection whose element type cannot be inferred (caught as [var-annotated]). One nuance is worth recording: the empty-list error fires only when nothing pins the element type. A second probe function that appends inside an if branch passed clean — mypy inferred list[int] from the append. So "annotate the empty collection" applies to collections that stay empty on some path, not to every results = [].

In the real file, the leak is page.evaluate(...). Playwright's evaluate returns Any: the value crosses from JavaScript into Python with no type at all, and every use of it downstream — if issues:, issue['tag'], issue['gap'] — inherits that Any. Annotating the definitions did not touch it. Step 3 is where it gets a real type.

Step 3: TypedDict at the JavaScript boundary

The JavaScript in the page returns two shapes of issue object. A crowded heading returns tag, text, reason, and topGap/bottomGap — but only the gaps that apply: a heading too close above has no bottomGap key, and one too close below has no topGap key. A tight section returns tag, id, gap, and reason. The Python side must model exactly that, including the missing keys, or the types lie about the data:

Python
from typing import Literal, NotRequired, TypedDict, cast

class H2Issue(TypedDict):
    tag: Literal["H2"]
    text: str
    topGap: NotRequired[int]
    bottomGap: NotRequired[int]
    reason: str

class SectionIssue(TypedDict):
    tag: Literal["SECTION"]
    id: str
    gap: int
    reason: str

type SpacingIssue = H2Issue | SectionIssue

class PageResult(TypedDict):
    page: str
    issues: list[SpacingIssue]

NotRequired is doing real work here: it records that the JavaScript omits the key, so the Python code must check for it before reading it. A TypedDict with all keys required would have passed mypy and been wrong about the data — the cast below would have hidden the mismatch either way, which is why the key optionality has to be decided from the JavaScript, not from the checker.

The alias uses the type statement from PEP 695, which is the same syntax step 6 covers in full. The boundary itself needs one cast, because page.evaluate returns Any and there is no type-safe way to claim a JavaScript value has a Python shape:

Python
issues = cast(
    list[SpacingIssue],
    page.evaluate("""... the JavaScript from the original script, unchanged ..."""),
)

A cast is a claim, not a check: if the JavaScript returns a different shape, the cast still passes and the failure moves to runtime. That is the honest cost of a JavaScript boundary, and it is why the TypedDict definitions above are written from the JavaScript source rather than from what the Python code happens to read.

With the cast in place, check_spacing returns list[PageResult] and main reads the results through the union. The tag check narrows the union, so issue['id'] and issue['gap'] are only reachable on the section branch and issue['text'] only on the heading branch:

Python
for issue in page_result['issues']:
    if 'tag' in issue and issue['tag'] == 'SECTION':
        print(f"  [SECTION #{issue['id']}] gap: {issue['gap']}px ({issue['reason']})")
    else:
        gaps = []
        if 'topGap' in issue: gaps.append(f"top: {issue['topGap']}px")
        if 'bottomGap' in issue: gaps.append(f"bottom: {issue['bottomGap']}px")
        print(f"  [{issue['tag']}] '{issue['text']}' {' '.join(gaps)} ({issue['reason']})")

The final run:

Terminal
$ mypy --strict --show-error-codes check_spacing.py
Success: no issues found in 1 source file

This time the clean run means something: the only Any left in the file is the *args/**kwargs passthrough on the request handler and the single cast at the JavaScript boundary, both deliberate. The typed script was then run against the live built site — it reported no spacing issues and exited 0 — and the original untyped script produced the same output, so the migration changed no behavior.

Step 4: every ignore carries its code

No # type: ignore was needed anywhere in this migration, which is the point: an ignore should be the last resort, and when one is needed it must carry its error code. A probe shows why. Four functions, four ignores:

Python
def bare_ignore() -> int:
    x: str = 1  # type: ignore
    return 0

def coded_ignore() -> int:
    y: str = 2  # type: ignore[assignment]
    return 0

def wrong_code_ignore() -> int:
    z: str = 3  # type: ignore[attr-defined]
    return 0

def stale_ignore() -> int:
    w: str = "ok"  # type: ignore[assignment]
    return 0
Terminal
$ mypy --strict --show-error-codes probe-ignore.py
probe-ignore.py:19: error: Unused "type: ignore" comment  [unused-ignore]
probe-ignore.py:19: error: Incompatible types in assignment (expression has type "int", variable has type "str")  [assignment]
probe-ignore.py:19: note: Error code "assignment" not covered by "type: ignore[attr-defined]" comment
probe-ignore.py:24: error: Unused "type: ignore" comment  [unused-ignore]
Found 3 errors in 1 file (checked 1 source file)

The bare ignore and the correctly coded ignore both silence their error and pass. The wrong-code ignore fails twice: the real [assignment] error is still reported, with a note saying the ignore did not cover it, and the ignore itself is flagged [unused-ignore] because it silenced nothing. The stale ignore — the underlying code is already correct — is flagged the same way. That second flag is the one that matters for a migration: --warn-unused-ignores is part of --strict, so every ignore left behind by an earlier fix gets reported the next time the code changes. A bare ignore never gets that treatment for the wrong reason — it silences whatever error happens to be on the line, including a new one introduced later. The rule for this codebase is simple: an ignore without a code does not ship.

Step 5: Protocol or ABC — the shape decision

The migration surfaces one shape decision, in the local HTTP server. serve_dist builds a ReusableTCPServer and calls four methods on it: server_address, serve_forever, shutdown, and the context-manager protocol. Nothing else about the server matters to the caller. The question is how to write that shape down: an abstract base class or a Protocol.

A probe shows the difference. First, the mutable-attribute rule that decides most Protocol designs:

Python
from typing import Protocol

class HasValue(Protocol):
    value: object

class Impl:
    def __init__(self) -> None:
        self.value: int = 1

def use(h: HasValue) -> None:
    h.value = "replaced"

use(Impl())
Terminal
$ mypy --strict --show-error-codes probe-protocol.py
probe-protocol.py:24: error: Argument 1 to "use" has incompatible type "Impl"; expected "HasValue"  [arg-type]
probe-protocol.py:24: note: Following member(s) of "Impl" have conflicts:
probe-protocol.py:24: note:     value: expected "object", got "int"

The implementation is rejected even though int is a subtype of object, because a mutable attribute in a Protocol is invariant: the protocol promises that any object can be written through value, and the implementation can only hold an int. Methods are fine with subtyping; writable attributes are not. If the attribute were read-only — declared with @property — the implementation would pass. That is the first thing to check when a Protocol refuses a class that looks compatible.

Second, the inheritance difference, from the same probe run:

Python
from abc import ABC, abstractmethod

class ClosableABC(ABC):
    @abstractmethod
    def close(self) -> None: ...

class FileHandle:
    def close(self) -> None:
        pass

class Closable(Protocol):
    def close(self) -> None: ...

def shutdown_abc(c: ClosableABC) -> None:
    c.close()

def shutdown_proto(c: Closable) -> None:
    c.close()

shutdown_proto(FileHandle())  # passes
shutdown_abc(FileHandle())    # error: Argument 1 has incompatible type "FileHandle"

FileHandle satisfies the Protocol without inheriting from anything, because structural subtyping only asks whether the methods exist. The abstract base class demands inheritance, so the same class fails. The decision rule that falls out of this: use a Protocol when the caller only needs "has these methods" — the server in serve_dist is that case — and use an ABC when the classes must share implementation or be registered in one hierarchy. A Protocol is also the only one of the two that works for classes you do not control, such as a third-party server class.

One runtime rule belongs with this step. The typing documentation states that a Protocol class without @runtime_checkable cannot be used with isinstance(), and that a runtime-checkable protocol checks only the presence of the required attributes, not their signatures. Both were confirmed on the installed Python 3.12.3: isinstance against a plain Protocol raises TypeError: Instance and class checks can only be used with @runtime_checkable protocols, and an object with a name attribute of the wrong type still passes an isinstance check against a @runtime_checkable protocol that requires name: str. A runtime protocol check is a presence check, never a type check.

Step 6: the PEP 695 conversion

The last step converts the generic container to the PEP 695 syntax. The migration's own containers are concrete TypedDicts and need no generics, so the conversion is demonstrated on the generic container the results list wants to be — a box holding one typed value — written both ways so the behavior can be compared:

Python
from typing import Generic, TypeVar

T = TypeVar("T")

class LegacyBox(Generic[T]):
    def __init__(self, value: T) -> None:
        self.value = value

    def get(self) -> T:
        return self.value

class Box[T]:
    def __init__(self, value: T) -> None:
        self.value = value

    def get(self) -> T:
        return self.value

type IntOrStrList[T] = list[T] | set[T]

def first[T](items: list[T]) -> T:
    return items[0]
Terminal
$ mypy --strict --show-error-codes probe-pep695.py
probe-pep695.py:38: note: Revealed type is "int"
probe-pep695.py:39: note: Revealed type is "int"
probe-pep695.py:40: note: Revealed type is "int"
Success: no issues found in 1 source file

The new syntax drops the TypeVar declaration and the Generic base class, and reveal_type confirms both versions infer the same type. The type statement form of the alias is the same one step 3 used for SpacingIssue. Three rules from the PEP are worth keeping with the conversion. First, mixing the two syntaxes is a runtime error, confirmed on the installed Python:

Terminal
$ python3 probe-runtime.py
TypeError: Cannot inherit from Generic[...] multiple times.

class Bad[T](Generic[T]) raises that TypeError at import time. Second, the new syntax changes variance: type parameters declared with the new syntax always infer their variance from use, while a traditional TypeVar keeps whatever variance its constructor declared. Third, a generic Protocol under the new syntax takes no arguments in its base class — class Bad[S, T](Protocol[S, T]) is an error, and mypy 2.4.0 reports it:

Output
probe-pep695b.py:9: error: No arguments expected for "Protocol" base class  [misc]

The runtime introspection still works: Box.__type_params__ is (T,), and Box[int](3).value is 3. The conversion target is the new syntax throughout — a file that mixes TypeVar generics with type statements is a file mid-migration, and this guide finishes the job rather than leaving both forms in place.

What breaks, and the fix

Symptom Error code Fix
Third-party import not found although the package is installed import-not-found Point mypy at the right interpreter (--python-executable, or python_executable in mypy.ini); do not install stubs for a package that ships py.typed
Function without annotations no-untyped-def Annotate the definition; annotate *args/**kwargs as Any where the signature is a passthrough
Call to an unannotated function no-untyped-call Annotate the callee — the error is reported at the call site but the fix is in the definition
Bare generic in a signature type-arg Supply the parameter: list[int], not list
Any returned from a typed function no-any-return Return the declared type, or cast at the boundary where the Any enters and say so
Empty collection with no inferable element type var-annotated Annotate the variable: results: list[PageResult] = []
Ignore that silences the wrong error, or nothing at all unused-ignore Give the ignore its code: # type: ignore[assignment]
Class rejected by a Protocol over a writable attribute arg-type Make the attribute read-only with @property, or widen the implementation's attribute type
Protocol[S, T] under the new syntax misc Drop the arguments: class P[S, T](Protocol)
Generic[T] mixed with new-style type parameters runtime TypeError Remove the Generic base class — the new syntax implies it

Frequently asked questions

Should I turn on --strict for the whole codebase at once?

The order in this guide is the answer: interpreter first, then annotations, then Any elimination. A whole-codebase switch produces the first list — imports plus missing annotations — and the annotation pass is mechanical. The Any work after that is judgment, one boundary at a time, and it is better done after the file already passes, when each new error is a decision rather than noise.

Does --strict catch Any?

Mostly no. Strict mode catches bare generics, Any returns, and unannotated definitions, but an Any value flowing through annotated code passes silently — step 1 of this migration proved it. If Any elimination is the goal, it is a separate pass with its own review, not a flag.

When is an ABC better than a Protocol?

When the classes need shared behavior or a common hierarchy. A Protocol describes a shape; it cannot provide an implementation. If two classes must share a method body, that body has to live in a base class, and the base class is the ABC.

Can I use isinstance with a Protocol?

Only with @runtime_checkable, and only as a presence check. A runtime-checkable protocol confirms the attributes exist; it does not check their types or signatures. Do not use it where the type matters — that is what the static check is for.

Is the same migration worth reading in TypeScript?

Yes. Turning strict On in a Codebase That Never Had It: TypeScript 5.9 to 7.0 runs the same job from the other side: a codebase that never set strict passes the older compiler clean, then reports its errors under the newer ones. The guide reads the error classes, fixes the config pair first, and takes the count to zero.

Sources

  • mypy, The mypy command line — the --strict flag list and the flags it enables, including the note that the list changes over time and that --warn-unreachable is not enabled by strict mode.
  • PEP 695, Type Parameter Syntax — the new type parameter syntax, the type statement, the runtime error for mixing Generic[T] with the new syntax, variance inference, and the Protocol[S, T] rule.
  • Python, typing — Support for type hints — Protocol and structural subtyping, @runtime_checkable presence-only checks, and TypedDict with NotRequired keys.

Keep Exploring