Type Hints Pay Off Only If You Run a Type Checker in CI

Python type hints have a dirty secret: the interpreter ignores them. def total(x: int) -> int will happily accept a string and return a list. Nothing checks it at runtime unless you add a library that does. Annotations are metadata. Nothing more.

So here's the position: type hints without a type checker in CI are decorative comments that can lie. Worse than no hints, because they look authoritative. If you're going to write them, make a machine verify them on every pull request. If you're not going to do that, at least be honest that they're documentation.

Hints that lie

This is the failure mode in a codebase where hints are written but never checked:

def find_user(email: str) -> User:
    return User.objects.filter(email=email).first()

That annotation is false. .first() returns None when nothing matches. Every caller trusts the signature, skips the None check, and the bug surfaces as AttributeError: 'NoneType' object has no attribute 'name' in production, three calls away from the cause.

A type checker with the Django plugin flags this immediately: the function returns User | None, not User. The fix is one honest annotation:

def find_user(email: str) -> User | None:
    return User.objects.filter(email=email).first()

Now every caller is forced to handle the missing case, and the checker tells you which ones don't. That's the entire value proposition of typing: move a class of runtime errors to review time. It only works if something actually runs.

Pick a checker and stop debating

The mainstream options:

  • mypy - the original, maintained under the Python organisation, with a mature plugin system. If you use Django, the django-stubs plugin makes querysets and model fields understood. This is the default choice for Django projects.
  • pyright - Microsoft's checker, written in TypeScript and fast. It powers the Pylance extension in VS Code, so many developers already see its errors in their editor. Its inference is aggressive and its strict mode is strict.
  • Newer Rust-based checkers such as Astral's ty and Meta's Pyrefly are worth watching. Check their status before betting a large codebase on them.

My advice: Django-heavy codebase, start with mypy and django-stubs. Library or non-Django service, pyright is a great default. Either is far better than neither, and arguing about it for a sprint is worse than picking one today.

Gradual adoption that doesn't stall

The common mistake is turning on --strict across a 200,000-line codebase, seeing thousands of errors and giving up. Python typing is designed to be gradual. Use that.

Start permissive globally and strict where it matters:

# pyproject.toml
[tool.mypy]
python_version = "3.12"
plugins = ["mypy_django_plugin.main"]
warn_unused_ignores = true
warn_redundant_casts = true
no_implicit_optional = true
check_untyped_defs = true

[tool.django-stubs]
django_settings_module = "config.settings"

# New and critical code: no untyped functions allowed.
[[tool.mypy.overrides]]
module = ["billing.*", "orders.services", "orders.selectors"]
disallow_untyped_defs = true
disallow_any_generics = true
warn_return_any = true

# Third-party packages without stubs: don't let them block CI.
[[tool.mypy.overrides]]
module = ["legacy_vendor_sdk.*"]
ignore_missing_imports = true

Then ratchet:

  1. Week one: run the checker in CI on the whole repo with the permissive defaults. Fix or # type: ignore[code] the existing errors. The goal is a green baseline, not perfection.
  2. Every new module goes into the strict override list. New code is typed from birth.
  3. Every time you touch an old module for real work, add it to the strict list and fix what falls out. Leave the place better than you found it.
  4. Track the ignore count. grep -rc "type: ignore" in CI is crude and it works. The number should only go down.

warn_unused_ignores matters more than it looks. When you fix the underlying problem, the stale ignore becomes an error, so suppressions can't rot silently.

Wire it into CI, not just the editor

Editor squiggles are advisory. A red CI check is a rule. A minimal GitHub Actions job:

name: typecheck
on: [pull_request]
jobs:
  mypy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      - uses: actions/setup-python@v6
        with:
          python-version: "3.12"
      - run: pip install -r requirements-dev.txt
      - run: mypy .

Pin your checker version in requirements-dev.txt. Checkers get smarter with each release, which means an unpinned upgrade can turn a green build red on a Monday morning with no code change. Upgrade on purpose, in its own pull request.

Make the check required on the main branch. If it can be skipped, it will be.

Rules worth keeping

Typing everything perfectly isn't the goal. Typing the parts where bugs are expensive is.

  • Type the boundaries first. Public functions, service layers, anything another module calls. Internals of a twenty-line helper can wait.
  • Ban Any from spreading. Any is contagious: whatever touches it becomes unchecked. Use it at the edge, such as parsing raw JSON, then convert to a real type immediately.
  • Model data, don't pass dicts. A dict[str, Any] travelling through five functions is a bug farm. Use a dataclass for internal data and a TypedDict when the shape really is a dict, like a JSON payload.
  • Use Protocol for dependencies. It's structural typing: a fake in tests satisfies it without inheriting anything.
from decimal import Decimal
from typing import Protocol


class PaymentGateway(Protocol):
    def charge(
        self, *, customer_id: str, amount: Decimal, reference: str
    ) -> str: ...


def settle(gateway: PaymentGateway, customer_id: str, amount: Decimal) -> str:
    return gateway.charge(
        customer_id=customer_id, amount=amount, reference="manual"
    )
  • Every ignore carries an error code. # type: ignore[attr-defined], never a bare # type: ignore. Bare ignores hide every future error on that line too.
  • Use reveal_type() when confused. Drop it in, run the checker, read what it thinks. It beats guessing.
  • Don't fight the checker with cast(). Each cast is you overruling the machine. Sometimes you're right. Usually the type is wrong upstream.

What typing won't do

Be clear-eyed about it. A type checker won't validate data coming over the wire. Your request body is still untrusted bytes, and for that you want runtime validation: a serializer, Pydantic or a plain schema check. Typing also won't catch logic bugs where the types line up and the maths is wrong. That's what tests are for.

Types and tests aren't competitors. Types eliminate a whole category of tests you'd otherwise write: "what if this is None", "what if someone passes a string". Tests cover behaviour. Together they're cheaper than either alone.

The cost argument

The usual objection is speed: "annotations slow us down." For a throwaway script, sure, skip them. For code that lives longer than a quarter and is touched by more than one person, the trade usually goes the other way. Refactoring is where it shows. Rename a field, change a return type, split a function, and the checker gives you the list of every call site that needs to change. Without it, that list is "grep and hope".

Bottom line

A type hint is a promise. A type checker in CI is what makes the promise binding. Pick mypy or pyright, start permissive, make new code strict, ratchet old code as you touch it, and make the check required. If you're not going to run a checker, stop writing hints that might be wrong. Unverified types aren't documentation, they're rumours.

edit

Newsletter

Get new writing by email

Occasional notes on Python, Django, AWS and building software. No spam, unsubscribe anytime. Prefer a feed reader? RSS.