Static Type Checking with mypy

Published by Brayan K

mypy reads your type hints and checks your code without running it, catching whole classes of bugs before they reach production. Python stays dynamic at runtime, but mypy gives you the safety net of a typed language during development.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A useful check must actually run over the code you rely on

Annotations are useful only when a checker reads enough of the program to find a mistake. This lesson takes a small project from an apparently clean result to an explicit checking policy, then shows the escape hatches that can make that result misleading. Type Hints & Static Typing with mypy owns annotation syntax; Advanced Type Hints (Generics, Protocol, TypedDict) owns reusable type relationships.

Install the measured checker in a local virtual environment with python -m pip install mypy==2.4.1. The bundled browser checker cannot start with the dependencies currently available, so these examples need local Python. Normally run python -m mypy your_package tests. The executable examples use mypy.api.run so they can capture the real report and exit status without starting a shell.

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'def double(value: int) -> int:\n    return value * 2\n\ndouble("3")\n'
check(source)
print("checking finished")

# ✅ Expected output:
# exit: 1
# 4: error: Argument 1 to "double" has incompatible type "str"; expected "int"  [arg-type]
# checking finished

The checked source is text passed to mypy, not executed Python. The diagnostic points to the incompatible call; the wrapper then continues. Exit status zero means no reported checking errors for the selected scope and settings, not that the application is correct. The examples remove only the synthetic filename prefix from diagnostics, retaining line numbers, severity, message and error code.

An untyped function can hide a mistake behind a clean result

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'def broken():\n    count: int = "many"\n    return count\n'
check(source)
check(source, "--check-untyped-defs")

# ✅ Expected output:
# exit: 0
# 2: note: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs  [annotation-unchecked]
# exit: 1
# 2: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]

Default checking skips this unannotated function’s body. check_untyped_defs examines the body, so it can detect the explicitly typed local assignment. It does not invent precise parameter types for every untyped function; unannotated parameters can still be Any.

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'def double(value):\n    return value * 2\n\ndouble("3")\n'
check(source, "--check-untyped-defs")
check(source, "--strict")

# ✅ Expected output:
# exit: 0
# exit: 1
# 1: error: Function is missing a type annotation  [no-untyped-def]
# 4: error: Call to untyped function "double" in typed context  [no-untyped-call]

Strict mode is a bundle of checks, not a mathematical proof and not a runtime enforcement mode. Its exact bundle can evolve with mypy versions, which is why a project should pin its checker and review upgrades. Add useful types at interfaces instead of silencing the missing-annotation error.

Any and cast can remove the evidence a checker needs

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'from typing import Any\n\ndef size(value: Any) -> int:\n    return value.missing_method()\n'
check(source)
check(source, "--warn-return-any")

# ✅ Expected output:
# exit: 0
# exit: 1
# 4: error: Returning Any from function declared to return "int"  [no-any-return]

Any allows arbitrary member access and can flow into a declared return type. warn_return_any catches this return boundary, but it does not make the missing method safe. Prefer a concrete type, object with narrowing, or a protocol that describes the needed operation.

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'from typing import cast\n\nvalue = cast(int, "7")\nresult = value + 1\n'
check(source)
from typing import cast
value = cast(int, "7")
print(type(value).__name__)
try:
    print(value + 1)
except TypeError as problem:
    print(str(problem))

# ✅ Expected output:
# exit: 0
# str
# can only concatenate str (not "int") to str

The checker accepts the claim made by cast; Python still holds a string. Use int(value) when conversion is the intended runtime operation and handle invalid input. Use cast only when you have a justified invariant the checker cannot express, and keep the evidence close to that assertion.

Fix the contract or narrow the value instead of ignoring the error

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

before = 'def fee(value: int | None) -> int:\n    return value + 2\n'
after = 'def fee(value: int | None) -> int:\n    if value is None:\n        return 2\n    return value + 2\n'
check(before, "--strict")
check(after, "--strict")

# ✅ Expected output:
# exit: 1
# 2: error: Unsupported operand types for + ("None" and "int")  [operator]
# 2: note: Left operand is of type "int | None"
# exit: 0

The None branch is real runtime behavior as well as evidence for the checker. An assert can narrow too, but use a normal conditional and exception when validation must remain active under optimized Python. A correct annotation should describe all values the function genuinely accepts.

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'count: int = 3  # type: ignore[assignment]\n'
check(source, "--warn-unused-ignores")

# ✅ Expected output:
# exit: 1
# 1: error: Unused "type: ignore" comment  [unused-ignore]

If a checker limitation truly requires a suppression, name the specific error code and explain the reason in the project. warn_unused_ignores helps remove a suppression after its underlying issue disappears. Broad ignores and globally ignored missing imports can turn meaningful types into Any and conceal new mistakes.

Put the policy in a configuration file and check explicit roots

from pathlib import Path
from tempfile import TemporaryDirectory
import re
from mypy import api

with TemporaryDirectory() as folder:
    root = Path(folder)
    config = root / "mypy.ini"
    source = root / "receipt.py"
    config.write_text(
        "[mypy]\npython_version = 3.11\nstrict = True\nshow_error_codes = True\n",
        encoding="utf-8",
    )
    source.write_text(
        'def total(count: int, price: int) -> int:\n    return count * price\n\ntotal("2", 5)\n',
        encoding="utf-8",
    )
    report, errors, status = api.run([
        "--config-file", str(config), "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary", str(source),
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        match = re.search(r":(\d+): (error|note): (.*)", line)
        if match:
            print(match.group(1), match.group(2), match.group(3))

# ✅ Expected output:
# exit: 1
# 4 error Argument 1 to "total" has incompatible type "str"; expected "int"  [arg-type]

The configuration is an actual file consumed by mypy. Passing an explicit config path makes the example independent of a parent directory’s settings. A real project should keep that file in version control and use the same invocation locally and in CI. Select the package and tests deliberately; checking one convenient file does not check an entire repository.

mypy normally follows imports it can resolve, so excluding a file from initial recursive discovery is not the same as forbidding mypy from following it through an import. Missing third-party type information may need a typed package, a stub package or a small owned stub. Do not globally ignore every missing import just to make the report green.

from mypy import api

def check(source, *options):
    report, errors, status = api.run([
        "--python-version", "3.11", "--no-incremental",
        "--no-pretty", "--no-color-output", "--no-error-summary",
        "--show-error-codes", *options, "-c", source,
    ])
    if errors:
        raise RuntimeError(errors)
    print("exit:", status)
    for line in report.splitlines():
        print(line.removeprefix("<string>:"))

source = 'from typing import Protocol\n\nclass HasTotal(Protocol):\n    def total(self) -> int: ...\n\ndef receipt(source: HasTotal) -> int:\n    return source.total()\n\nclass Broken:\n    def total(self) -> str:\n        return "ten"\n\nreceipt(Broken())\n'
check(source, "--strict")

# ✅ Expected output:
# exit: 1
# 13: error: Argument 1 to "receipt" has incompatible type "Broken"; expected "HasTotal"  [arg-type]
# 13: note: Following member(s) of "Broken" have conflicts:
# 13: note:     Expected:
# 13: note:         def total(self) -> int
# 13: note:     Got:
# 13: note:         def total(self) -> str

The diagnostic compares the method signature the consumer needs with the one the object provides. No inheritance from the protocol is required. This is a checked use of the structural typing concept owned by Advanced Type Hints (Generics, Protocol, TypedDict).

Make gradual adoption measurable

For an existing project, choose a real boundary such as parsing an input record and returning a typed domain object. Annotate its callers and tests, run the checker, then expand the checked scope. Keep temporary per-module exceptions narrow and record why they remain. A smaller honestly checked area is more useful than claiming whole-project safety while broad Any values cross every boundary.

Static checking, runtime validation and tests answer different questions. mypy checks declared relationships without running the program; Data Validation with Pydantic checks incoming values at runtime; tests exercise behavior with selected inputs. Keep all three where the project needs them. No tool proves that an arithmetic formula or business requirement is the right one.

Complete a typed optional-value boundary

The source text is the program being checked. Fill its return annotation with int and its condition with is None. Run strict checking, then execute the accepted program to demonstrate both branches.

from mypy import api

source = """def count_or_zero(value: int | None) -> ___:
    if value ___:
        return 0
    return value

print(count_or_zero(None), count_or_zero(4))
"""
report, errors, status = api.run([
    "--python-version", "3.11", "--strict", "--no-incremental",
    "--no-error-summary", "--no-pretty", "--no-color-output", "-c", source,
])
if errors:
    raise RuntimeError(errors)
print("exit:", status)
print("diagnostics:", bool(report))
exec(source)

# 👉 replace ___ with int
# 👉 replace ___ with is None

# ✅ Expected output:
# exit: 0
# diagnostics: False
# 0 4

Check a parser contract and its callers

Write a typed parse_count(text) function that returns a nonnegative integer or None for invalid or negative text. Add a typed formatter that handles both outcomes. Run strict mypy checking over the complete source and then execute it with "4", "-2" and "many". Do not use Any, cast or type: ignore to silence a mismatch.

from mypy import api

source = """def parse_count(text: str) -> int | None:
    try:
        count = int(text)
    except ValueError:
        return None
    return count if count >= 0 else None

def label(text: str) -> str:
    count = parse_count(text)
    if count is None:
        return "invalid"
    return f"count={count}"

for text in ["4", "-2", "many"]:
    print(label(text))
"""
report, errors, status = api.run([
    "--python-version", "3.11", "--strict", "--no-incremental",
    "--no-error-summary", "--no-pretty", "--no-color-output", "-c", source,
])
if errors:
    raise RuntimeError(errors)
print("exit:", status)
print("diagnostics:", bool(report))
if status == 0:
    exec(source)

# ✅ Expected output:
# exit: 0
# diagnostics: False
# count=4
# invalid
# invalid

The runtime examples check the parser’s chosen nonnegative policy; mypy cannot infer that this is the right business rule. Before adding it to a project, decide whether spaces, a leading plus sign and other forms accepted by int belong in the input format, and add behavior tests for that decision.

Practice quiz

What does mypy normally do with source passed to its checker?

  • Analyze it without executing the application
  • Run every business operation
  • Validate every future HTTP request
  • Convert annotated values at runtime

Answer: Analyze it without executing the application. Static analysis reads the program; it does not execute its application behavior.

What does --check-untyped-defs add?

  • Automatic precise types for every parameter
  • Checks inside otherwise untyped function bodies
  • Runtime conversion
  • Guaranteed absence of Any

Answer: Checks inside otherwise untyped function bodies. It checks the body but unannotated parameters can still be Any.

Why pin the mypy version in a project?

  • Python requires it for all annotations
  • It prevents every runtime bug
  • Diagnostics and the strict-check bundle can change between versions
  • It replaces tests

Answer: Diagnostics and the strict-check bundle can change between versions. A reproducible checker version makes upgrades reviewable.

What does cast(int, "7") do at runtime?

  • Returns integer 7
  • Raises ValidationError
  • Changes Python’s string implementation
  • Returns the original string

Answer: Returns the original string. cast is a type-checker assertion, not a conversion.

Which setting identifies an unnecessary type: ignore comment?

  • warn_unused_ignores
  • ignore_missing_imports
  • follow_imports = skip
  • check_untyped_defs = False

Answer: warn_unused_ignores. Unused-ignore warnings help remove stale suppressions.

Why check explicit package and test roots in CI?

  • To force every value to be Any
  • To make the checked scope deliberate and repeatable
  • To run a web server
  • To avoid reading configuration

Answer: To make the checked scope deliberate and repeatable. A passing check only describes the selected scope and policy.

A function returns int | None. Which repair preserves that contract before addition?

  • cast(int, value) without evidence
  • Ignore the operator error
  • Handle None explicitly, then use the narrowed int
  • Remove every annotation

Answer: Handle None explicitly, then use the narrowed int. The conditional both handles the runtime case and narrows the type.

A project passes strict checking. What can still be wrong?

  • No function can return
  • All tests must fail
  • Python cannot execute it
  • Its formula or business rule can be incorrect

Answer: Its formula or business rule can be incorrect. Type consistency is only one kind of correctness.

Continue this course

Related lessons