You have a 50k-line Python codebase with no type hints. You want the safety and editor support that type checking brings, but you cannot stop feature work to annotate everything or risk breaking your CI pipeline with hundreds of new errors. This guide shows how to introduce Python type hints mypy checking incrementally: start with minimal configuration, silence existing violations, enable type checking for new code, and gradually tighten rules.
The key is gradual typing. You run mypy on the entire codebase from day one, but configure it to ignore legacy modules while enforcing checks on new files. Over weeks or months, you annotate hot paths and critical modules, tighten strictness settings one at a time, and delete suppression comments. This approach keeps builds green, avoids big-bang rewrites, and delivers value immediately: every new function you write gets checked.
Installing Mypy and Running Your First Check
Install mypy in your development environment with pip or add it to your project dependencies:
pip install mypy
For Poetry users, add it as a development dependency:
poetry add --group dev mypy
Run mypy on your project root to see what you're working with:
mypy .
Typical output for an unannotated codebase looks like this:
src/api/handlers.py:45: error: Function is missing a return type annotation [no-untyped-def]
src/api/handlers.py:67: error: Call to untyped function "process_data" in typed context [no-untyped-call]
src/models/user.py:12: error: Incompatible return value type (got "None", expected "str") [return-value]
Found 127 errors in 23 files (checked 45 source files)
Mypy performs static type checking: it reads your source code and infers or checks types without running the program. This catches type mismatches, missing return annotations, and calls to untyped functions. Unlike runtime validation libraries, mypy produces no overhead in production and integrates with editors for instant feedback. Alternatives exist: pyright (used by VS Code's Pylance) offers faster performance and pytype (Google's checker) infers more types automatically. Still, mypy remains the most widely adopted tool with the richest ecosystem of third-party type stubs in typeshed.
If you see errors about missing stubs for libraries like requests or numpy, install them:
mypy --install-types
This fetches type information for third-party packages from typeshed. Distinguish between two categories of errors: missing annotations (mypy complains your function has no type hints) and actual type errors (you return an int where a str is expected). The first category is noise in legacy code; the second catches real bugs.
Configuring Mypy for an Existing Codebase
A bare mypy . run on legacy code produces hundreds of errors. The solution is not to fix them all immediately but to configure mypy permissively, then tighten rules incrementally. Store configuration in pyproject.toml under a [tool.mypy] section or in a separate mypy.ini file.
Starting with a Permissive Configuration
Create a minimal pyproject.toml configuration that allows unannotated code:
[tool.mypy]
python_version = "3.11"
warn_return_any = false
disallow_untyped_defs = false
disallow_untyped_calls = false
check_untyped_defs = false
Set python_version to match your runtime. The disallow_untyped_* flags control strictness; all are false here so mypy does not complain about missing annotations. With this configuration, mypy only reports actual type errors in annotated functions. You can commit this immediately without breaking CI.
Using pyproject.toml vs mypy.ini
Most Python projects now use pyproject.toml for tool configuration. If your team prefers separate config files, create mypy.ini instead:
[mypy]
python_version = 3.11
warn_return_any = False
disallow_untyped_defs = False
The syntax differs slightly (True/False capitalized, no quotes). Both formats support the same options; choose whichever your project already uses for other tools. Mypy reads both files but mypy.ini takes precedence if both exist.
Per-Module and Per-Package Overrides
Exclude directories that should never be checked: tests, database migrations, vendored libraries.
[tool.mypy]
python_version = "3.11"
exclude = [
"^tests/",
"^migrations/",
"^vendor/",
]
For finer control, enable strict checks on new modules while leaving legacy code alone. Use [[tool.mypy.overrides]] sections to apply different rules to different paths:
[tool.mypy]
python_version = "3.11"
warn_return_any = false
disallow_untyped_defs = false
[[tool.mypy.overrides]]
module = "src.api.new_handlers"
disallow_untyped_defs = true
warn_return_any = true
[[tool.mypy.overrides]]
module = "src.legacy.*"
ignore_errors = true
The first override enables strict checks for src/api/new_handlers.py. The second silences all errors in the src/legacy package. Wildcards match submodules. This pattern lets you enforce types in new code immediately while deferring work on legacy modules. As you annotate more files, move them out of the ignore_errors override.
Handling Existing Type Violations Without Blocking CI
Even with permissive configuration, you will encounter errors in partially annotated code. Rather than remove all type hints or disable mypy entirely, suppress specific errors with inline comments.
Using # type: ignore Comments Strategically
Add # type: ignore to the end of a line to silence mypy for that statement:
result = legacy_function(data) # type: ignore
Better, specify the error code so you only suppress the expected issue:
result = legacy_function(data) # type: ignore[no-untyped-call]
Run mypy --show-error-codes to see codes like [no-untyped-call], [return-value], or [arg-type]. Specific ignores document why the suppression exists and prevent masking unrelated errors. Enable warn_unused_ignores in your configuration to catch stale comments when you fix the underlying issue:
[tool.mypy]
warn_unused_ignores = true
Use # type: ignore sparingly. If you find yourself adding it to dozens of lines in one module, use a per-module override instead. Reserve inline ignores for isolated cases where fixing the type error requires refactoring you will do later.
Generating a Baseline with mypy --warn-unused-ignores
For codebases with hundreds of existing violations, manually adding ignores is impractical. Create a baseline file that captures current errors so CI only fails on new ones. Run mypy and save the output:
mypy . > mypy-baseline.txt 2>&1 || true
The || true ensures the command succeeds even if mypy exits non-zero. In CI, compare new mypy output against the baseline and fail only if new errors appear. A simple wrapper script handles this:
#!/bin/bash
mypy . > mypy-current.txt 2>&1 || true
if ! diff -u mypy-baseline.txt mypy-current.txt; then
echo "New type errors detected"
exit 1
fi
This approach keeps CI green while preventing regressions. The downside: baseline files grow stale as code changes. Lines move, modules rename, and the baseline drifts. Schedule monthly or quarterly reviews to regenerate the baseline after fixing a batch of errors.
The mypy-baseline Tool for Large Codebases
For teams managing baselines across multiple branches, the third-party mypy-baseline tool automates this workflow. Install it alongside mypy:
pip install mypy-baseline
Generate a baseline file in JSON format:
mypy-baseline sync
In CI, check for new violations:
mypy-baseline check
The tool normalizes file paths and error messages, reducing false positives from line number shifts. It integrates with GitHub Actions and GitLab CI via exit codes. Trade-offs remain: baselines hide technical debt and require discipline to shrink over time. Pair baseline enforcement with a policy that new modules must pass strict checks, ensuring the baseline never grows.
Enabling Strict Checks Incrementally
Once mypy runs cleanly on your codebase (even if only because legacy code is suppressed), start tightening checks. The goal is to enable strictness flags one at a time, module by module, until the entire project runs under strict = true. This section shows how to enable specific checks, what each one catches, and the practical migration path.
Adding disallow_untyped_defs to New Modules
The most impactful early win is requiring type annotations on all new functions. Enable disallow_untyped_defs for a single module or package using a per-module override:
[[tool.mypy.overrides]]
module = "src.new_feature.*"
disallow_untyped_defs = true
Now every function in src/new_feature/ must have parameter and return type annotations. Mypy rejects code like this:
def process_order(order_id): # error: Function is missing a type annotation
return fetch_order(order_id)
Fix it by adding types:
def process_order(order_id: int) -> Order:
return fetch_order(order_id)
Enforce this rule on new modules from day one. For existing modules, enable check_untyped_defs = true first. It type-checks function bodies even when signatures lack annotations, catching bugs without forcing you to annotate everything immediately. Once a module's logic is clean, add full annotations and promote it to disallow_untyped_defs.
Enabling warn_unused_ignores and warn_redundant_casts
Two hygiene checks help keep your codebase clean as you annotate. Enable warn_unused_ignores to catch stale # type: ignore comments left behind after you fix the underlying issue:
[tool.mypy]
warn_unused_ignores = true
When you annotate a previously ignored function, mypy reports:
src/handlers.py:23: note: unused 'type: ignore' comment
Delete the comment. Similarly, warn_redundant_casts flags explicit casts that do nothing:
[tool.mypy]
warn_redundant_casts = true
If you write cast(str, some_string) where some_string is already inferred as str, mypy warns you. Both flags reduce noise and prevent ignores from masking future bugs. Enable them globally once your baseline is stable.
Moving Toward strict = True
The strict flag is a bundle of about a dozen checks: disallow_untyped_defs, disallow_any_generics, warn_return_any, warn_redundant_casts, warn_unused_ignores, disallow_untyped_calls, and more. Enable it for a single module to see what it enforces:
[[tool.mypy.overrides]]
module = "src.core.engine"
strict = true
Strict mode rejects untyped calls to other modules, requires annotations on all definitions, and forbids Any in generics. It catches more bugs but requires dependencies to be annotated or stubbed. The official mypy documentation lists every flag included in strict mode. Migrate module by module: annotate a file, enable strict for it, fix errors, repeat. Track progress with a checklist in your project documentation. Some teams set a goal like "all new modules strict by Q2, all core modules strict by Q4."
Integrating Mypy into CI/CD Pipelines
Running mypy locally is useful; running it in CI ensures no one merges unannotated code or introduces type errors. This section shows how to integrate mypy into GitHub Actions and GitLab CI, cache type-checker state for faster builds, and handle errors gracefully during gradual adoption.
Running Mypy in GitHub Actions and GitLab CI
A minimal GitHub Actions workflow step installs dependencies and runs mypy:
- name: Run mypy
run: |
pip install mypy
mypy --no-incremental .
The --no-incremental flag disables mypy's cache, forcing a full check every run. Incremental mode is faster locally because mypy reuses type information from previous runs, but in CI it can produce false positives if the cache becomes stale or the runner's file timestamps differ from your local machine. Always use --no-incremental in CI for deterministic results.
For GitLab CI, add a job to your .gitlab-ci.yml:
mypy:
image: python:3.11
script:
- pip install mypy
- mypy --no-incremental .
Both examples assume you committed a pyproject.toml or mypy.ini configuration. If your project uses Poetry or pipenv, install mypy from the lockfile instead of manually. For projects with many dependencies, install type stubs in a separate step to keep output readable:
- run: mypy --install-types --non-interactive
- run: mypy --no-incremental .
Caching Type-Checker State for Faster Builds
Even with --no-incremental, mypy must parse and analyze your entire codebase on every CI run. For large projects, this takes minutes. Speed it up by caching the .mypy_cache directory between runs. In GitHub Actions, use actions/cache:
- name: Cache mypy
uses: actions/cache@v3
with:
path: .mypy_cache
key: mypy-${{ runner.os }}-${{ hashFiles('pyproject.toml') }}
- name: Run mypy
run: mypy .
Remove --no-incremental when caching. The cache key includes your configuration file hash so mypy rebuilds the cache when you change strictness settings. On a 50k-line codebase, caching can cut mypy runtime from 90 seconds to 20 seconds. In GitLab CI, use the built-in cache directive:
mypy:
cache:
paths:
- .mypy_cache
script:
- mypy .
Cache hits depend on runners reusing the same filesystem. If your CI provider assigns a fresh runner every time, caching provides no benefit. Test both approaches and measure.
Handling mypy Errors as Warnings in Pull Requests
During gradual adoption, you may want mypy to run in CI without blocking merges. Set continue-on-error: true in GitHub Actions:
- name: Run mypy
continue-on-error: true
run: mypy .
The step runs, logs output, but the workflow succeeds even if mypy finds errors. This keeps builds green while giving developers visibility into type issues. For a better developer experience, integrate reviewdog to post mypy findings as inline PR comments. Install reviewdog in your workflow and pipe mypy output to it:
- name: Run mypy with reviewdog
env:
REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
mypy . | reviewdog -f=mypy -reporter=github-pr-review
Reviewdog parses mypy's output format and creates review comments on the exact lines with errors. Developers see type issues in context without leaving the pull request. This approach works well when you want visibility without enforcement. Once your baseline shrinks and new code is fully typed, switch to failing CI on any mypy error.
Annotating Code: Practical Patterns and Common Pitfalls
Once mypy runs in CI, you need to actually annotate functions. This section shows common patterns, how to handle complex types, and techniques to avoid circular imports that appear only during type checking.
Function Signatures and Return Types
Every function should declare parameter types and a return type. Use -> None for functions that return nothing:
def log_event(message: str, level: int) -> None:
print(f"[{level}] {message}")
For functions returning collections, specify the element type using brackets:
def get_user_ids() -> list[int]:
return [1, 2, 3]
def load_config() -> dict[str, str]:
return {"host": "localhost", "port": "5432"}
If a dictionary has mixed value types, use Any but sparingly:
from typing import Any
def parse_response() -> dict[str, Any]:
return {"status": 200, "data": [1, 2, 3], "cached": True}
Overusing Any defeats the purpose of type checking. If you know the structure, use TypedDict instead:
from typing import TypedDict
class Response(TypedDict):
status: int
data: list[int]
cached: bool
def parse_response() -> Response:
return {"status": 200, "data": [1, 2, 3], "cached": True}
Now mypy verifies that all required keys exist and their types match. This catches bugs where you misspell a key or return the wrong type.
Generic Types, Union, and Optional
Use Optional[T] or T | None (Python 3.10+) for values that might be absent:
from typing import Optional
def find_user(user_id: int) -> Optional[User]:
user = db.query(User).get(user_id)
return user # might be None
Python 3.10 introduced the pipe syntax, which is clearer:
def find_user(user_id: int) -> User | None:
return db.query(User).get(user_id)
Both forms are equivalent; choose based on your minimum supported Python version. For functions accepting multiple types, use Union or the pipe:
from typing import Union
def format_id(user_id: Union[int, str]) -> str:
return str(user_id)
# Python 3.10+
def format_id(user_id: int | str) -> str:
return str(user_id)
Mypy narrows the type inside conditional branches. If you check isinstance(user_id, int), mypy knows user_id is an int in that block. Use cast() when mypy cannot infer the type but you know it's safe:
from typing import cast
def process_data(data: Any) -> str:
# We know data is a dict from external validation
return cast(dict[str, str], data)["key"]
Unlike # type: ignore, cast() documents the expected type and still checks that the cast makes sense. Use it when parsing JSON, deserializing data, or working with dynamic frameworks where static analysis falls short.
Using TYPE_CHECKING to Avoid Circular Imports
Type annotations sometimes require imports that create circular dependencies. For example, a User model references an Order model, and Order references User. Import the types only during type checking using TYPE_CHECKING:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .models import Order
class User:
def get_orders(self) -> list["Order"]:
return []
The if TYPE_CHECKING block runs only when mypy analyzes the file, not at runtime. Use a forward reference (the string "Order") in the annotation. Python 3.7+ supports from __future__ import annotations, which makes all annotations strings automatically, eliminating the need for quotes:
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .models import Order
class User:
def get_orders(self) -> list[Order]: # no quotes needed
return []
This approach keeps imports clean and avoids runtime overhead. It is standard practice in large codebases where circular dependencies are common.
Mypy Performance and Troubleshooting
On codebases with tens of thousands of lines, mypy can take minutes to run. This section shows how to speed it up, debug obscure errors, and handle third-party libraries without type stubs.
Speeding Up Mypy with mypyc and Parallelization
Mypy's incremental mode caches type information between runs. Enable it by default in pyproject.toml:
[tool.mypy]
incremental = true
cache_dir = ".mypy_cache"
After the first run, mypy only rechecks modified files and their dependencies. On a 30k-line project, incremental mode cuts subsequent runs from 45 seconds to under 10 seconds. The cache lives in .mypy_cache; add it to .gitignore. If you see inconsistent errors, delete the cache and rerun:
rm -rf .mypy_cache && mypy .
For even faster checks, install mypyc, which compiles mypy itself to C extensions:
pip install mypy[mypyc]
Mypyc is experimental but can halve runtime on large projects. Test it locally before deploying to CI. Mypy does not parallelize by default, but you can split checks across modules manually. Run mypy on subdirectories in parallel with GNU parallel or xargs:
find src -type d -maxdepth 1 | parallel mypy
This works if your modules are independent. If they share types, parallel runs may produce inconsistent results. For most teams, incremental mode and mypyc provide enough speedup without complexity.
Debugging Obscure Type Errors with --show-error-codes
Mypy error messages sometimes lack context. Enable --show-error-codes to see which rule is violated:
mypy --show-error-codes .
Output now includes codes in brackets:
src/handlers.py:34: error: Argument 1 to "process" has incompatible type "str"; expected "int" [arg-type]
The [arg-type] code tells you this is an argument type mismatch. Use codes to write specific # type: ignore comments or search the mypy documentation for details. Enable error codes globally in configuration:
[tool.mypy]
show_error_codes = true
For deeply nested generic errors, use --show-traceback to see mypy's internal reasoning:
mypy --show-traceback .
This dumps a Python traceback showing where mypy's type inference failed. It is verbose but helps when an error message like "incompatible type in assignment" appears on a line with no obvious issue. Most of the time, the error is on a different line; mypy reports where the mismatch is detected, not where it originates.
Dealing with Third-Party Libraries Without Stubs
Many libraries lack type stubs. When you import them, mypy complains:
src/app.py:3: error: Library stubs not installed for "requests" [import]
Install stubs from typeshed if they exist:
pip install types-requests
Run mypy --install-types to install all missing stubs automatically. If no stubs exist, silence the error per module:
[[tool.mypy.overrides]]
module = "some_library.*"
ignore_missing_imports = true
This tells mypy to treat some_library as if all its types are Any. You lose type safety for calls into that library, but your own code still gets checked. For libraries you control or use heavily, write a stub file. Create stubs/some_library.pyi and declare types:
def fetch_data(url: str, timeout: int) -> dict[str, str]: ...
The .pyi extension marks this as a stub. Add the stubs directory to mypy's search path:
[tool.mypy]
mypy_path = "stubs"
Now mypy uses your stub instead of complaining about missing imports. For widely used libraries, consider contributing stubs to the typeshed repository so the entire Python community benefits.
Mypy Rollout Checklist and Next Steps
You have installed mypy, configured it for gradual adoption, integrated it into CI, and started annotating code. Here is a practical checklist to ensure your rollout succeeds and a path forward for deepening your Python expertise.
Rollout checklist:
- Install mypy and run it locally; document how many errors exist today.
- Create a permissive
pyproject.tomlconfiguration; commit it and verify CI passes. - Generate a baseline or add per-module overrides for legacy code.
- Enable
disallow_untyped_defsfor all new modules via an override pattern. - Add mypy to CI with
--no-incrementalor caching; ensure it runs on every pull request. - Enable
warn_unused_ignoresandwarn_redundant_castsglobally. - Annotate one critical module per week; move it to strict mode when clean.
- Schedule quarterly reviews to regenerate baselines and delete fixed ignores.
- Set a team goal: all new code strict by a specific date, all core modules strict within a year.
Type checking is one piece of writing robust Python. For deeper coverage of Python's object model, class design, and advanced patterns like descriptors and metaclasses, see Mastering Python Object-Oriented Programming. It covers type hints in the context of larger architectural decisions and shows how to design APIs that are both type-safe and Pythonic.
As your codebase grows, consider running mypy in daemon mode (dmypy) for instant feedback during development. Investigate pyright if mypy performance becomes a bottleneck. Pair type checking with runtime validation libraries like pydantic for API boundaries where external data enters your system. The combination of static and runtime checks catches bugs that neither approach finds alone.
Frequently Asked Questions
Should I use mypy or pyright for type checking Python?
Mypy is the most widely adopted and has the richest ecosystem of third-party stubs. Pyright, developed by Microsoft and used in VS Code's Pylance, is faster and catches some errors mypy misses, but its configuration is less mature. For most teams, start with mypy because of community support and documentation. Switch to pyright if you need better performance on very large codebases or tighter VS Code integration. Both tools follow PEP 484 and produce similar results on well-annotated code.
How do I add type hints to a large codebase without breaking everything?
Use gradual typing: configure mypy permissively so it only checks annotated functions, suppress existing errors with per-module overrides or a baseline file, and enable strict checks for new code via [[tool.mypy.overrides]] sections. Annotate one module per week, starting with critical paths or frequently changed files. Run mypy in CI from day one but allow it to pass even with errors during the transition. This keeps builds green while steadily increasing type coverage.
What is the difference between # type: ignore and cast() in mypy?
# type: ignore suppresses all type errors on a line, telling mypy to skip checking it entirely. cast() asserts a specific type without disabling checks; it documents what you expect and mypy still verifies the cast is plausible. Use cast() when you know a value's type from external context (like JSON parsing) but mypy cannot infer it. Use # type: ignore only for cases where fixing the error requires major refactoring you will do later. Always prefer # type: ignore[error-code] to suppress only the specific issue.
Can I run mypy on code that still supports Python 3.8?
Yes. Set python_version = "3.8" in your mypy configuration and avoid syntax introduced in later versions, like the | union operator (use Union instead) or built-in generic types without importing from typing (use List[int] not list[int]). Mypy checks that your annotations are valid for the target version. You can develop on Python 3.11 and still type-check for 3.8 compatibility, but test runtime behavior on the actual version you deploy.
How do I make mypy faster in CI for a large repository?
Use --no-incremental to avoid stale cache issues, but cache the .mypy_cache directory between CI runs using actions/cache or your CI provider's cache mechanism. Install mypy[mypyc] to use the compiled version of mypy, which can halve runtime. For very large monorepos, split checks across independent modules and run them in parallel. If mypy still takes too long, evaluate pyright, which is faster on large codebases but requires migrating configuration and may behave differently on edge cases.