A function annotated to take an integer was handed the string "ab" and returned "abab". Python ran it without a word of complaint. That is the first thing to understand about type hints: the interpreter does not check them. The typing module documentation says it in one line: “The Python runtime does not enforce function and variable type annotations.” Checking is the job of a separate tool, and mypy is the oldest and most widely used of them. A handful of small files run through mypy 2.4.1 on Python 3.13 show what that tool catches, what it skips by default and where an annotation quietly turns the checker off.
Annotations are labels, not locks
The runtime shrug
The test that opens this post is three lines:
def double(x: int) -> int:
return x * 2
print(double("ab"))Run with python3, it prints abab. String repetition is perfectly legal Python, the annotation is just metadata attached to the function, and nothing reads it at call time. The typing docs say annotations “can be used by third party tools such as type checkers, IDEs, linters, etc.” That list is the whole audience.
The checker’s view
Run the same file through mypy ex6.py and the result is different:
ex6.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]
mypy never executes the file. The mypy getting started guide describes the tool as checking “for errors without ever running your code.” It reads the annotations, follows the values through the program and reports mismatches. Adding reveal_type(double(2)) to the file made mypy print Revealed type is "int", a handy way to ask the checker what it believes about any expression.

Catching bad arguments
A list that was a string
The first example is the most ordinary bug there is:
def average(values: list[float]) -> float:
return sum(values) / len(values)
print(average([1, 2, 3]))
print(average("123"))At runtime the second call crashes inside sum() with TypeError: unsupported operand type(s) for +: 'int' and 'str', a message that points at the wrong line for anyone reading the traceback quickly. mypy reported the real problem at the call site:
ex1.py:5: error: Argument 1 to "average" has incompatible type "str"; expected "list[float]" [arg-type]
Integers where floats were promised
The first call, average([1, 2, 3]), passed without complaint even though the list holds integers and the annotation says list[float]. mypy treats int as acceptable where float is expected, which matches how Python numbers behave in practice. That special case is the kind of detail worth knowing before assuming the checker is being lenient by mistake.
The None that bites later
Optional return values
A huge share of real crashes are AttributeError: 'NoneType' object has no attribute .... Type hints make that risk visible:
def find_user(user_id: int) -> str | None:
users = {1: "ann", 2: "bob"}
return users.get(user_id)
name = find_user(3)
print(name.upper())mypy flagged the last line:
ex2.py:6: error: Item "None" of "str | None" has no attribute "upper" [union-attr]
Narrowing
The fix is to prove to the checker that the value is not None before using it, with an if name is not None: check or an early return. mypy follows that logic and narrows the type to plain str inside the guarded block. The annotation str | None is honest about what dict.get() returns, and honesty at the function boundary is what lets the checker do its job further down.

Typos, bad modes and reassigned constants
TypedDict
Code that passes dictionaries around, such as rows parsed from JSON or CSV, gets no help from a plain dict[str, float] annotation when a key is misspelled. TypedDict declares the expected keys:
from typing import TypedDict
class Row(TypedDict):
sku: str
price: float
def total(rows: list[Row]) -> float:
return sum(r["price"] for r in rows)
total([{"sku": "a1", "price": 3.5}, {"sku": "b2", "prise": 4.0}])mypy caught the typo from both directions:
ex4.py:10: error: Missing key "price" for TypedDict "Row" [typeddict-item]
ex4.py:10: error: Extra key "prise" for TypedDict "Row" [typeddict-unknown-key]
At runtime, the same call would raise KeyError: 'price' inside total(), again one step removed from the line that caused it.
Literal for allowed values
Functions that accept a mode string, such as "r" or "a", usually document the allowed values in a docstring that nobody checks. Literal turns that list into something mypy enforces:
from typing import Final, Literal
MAX_RETRIES: Final = 3
MAX_RETRIES = 5
def open_log(mode: Literal["r", "a"]) -> None:
print(mode)
open_log("w")mypy reported both mistakes in this seven-line file:
ex7.py:4: error: Cannot assign to final name "MAX_RETRIES" [misc]
ex7.py:9: error: Argument 1 to "open_log" has incompatible type "Literal['w']"; expected "Literal['r', 'a']" [arg-type]
Final for constants
Python has no real constants. A module-level MAX_RETRIES = 3 can be reassigned anywhere, and a test that sets it to 0 and forgets to put it back can poison the next hundred tests. Marking it Final does not stop the reassignment at runtime either, but the checker refuses it, which is usually enough to stop the mistake before it reaches a commit.
Both annotations cost one import and a few characters. Neither changes how the program runs.
Where mypy goes quiet
Unannotated functions are skipped
This is the surprise that catches people adding mypy to an existing project. The getting started guide is explicit: “A function without type annotations is considered to be dynamically typed by mypy,” and “By default, mypy will not type check dynamically typed functions.”
def greet(name):
return "hi " + name
greet(5)
def greet2(name: str):
return "hi " + name
greet2(5)Plain mypy ex3.py reported only one error, on greet2(5). The identical bug in greet(5) passed, because greet has no annotations. A clean mypy run on a mostly unannotated codebase means very little.
Strict mode
The same file under mypy --strict produced four errors: Function is missing a type annotation for greet, Call to untyped function "greet" in typed context, Function is missing a return type annotation for greet2, and the original argument error. The mypy guide says strict mode “enables a number of additional checks, like –disallow-untyped-defs,” and warns that it may be too aggressive for large existing codebases. A common path is to start without it and turn individual strict checks on as coverage grows.
Any switches the checker off
The last trap is the Any type. The typing docs describe it as a “Special type indicating an unconstrained type,” and note that every type is assignable to Any and Any is assignable to every type. In practice that means mypy stops checking anything that touches it:
def load(path: str) -> Any:
with open(path) as f:
return json.load(f)
cfg = load("x.json")
cfg.this_does_not_exist()mypy accepted cfg.this_does_not_exist() without comment. Changing the return annotation to dict[str, object] made the next line, cfg2["port"] + 1, fail with Unsupported operand types for + ("object" and "int"), which is the checker correctly refusing to assume a JSON value is a number. The stricter annotation forces an explicit check or conversion before the value is used.

Configuring mypy for a real project
pyproject.toml
Typing command-line flags gets old quickly. mypy reads settings from pyproject.toml; the configuration file documentation says the usual [mypy] section “should have tool. prepended to its name.” Per-module settings go in [[tool.mypy.overrides]] tables, each with a module key. That makes it possible to be strict where new code lives and relaxed where old code waits:
[tool.mypy]
python_version = "3.13"
warn_unused_ignores = true
[[tool.mypy.overrides]]
module = "core"
disallow_untyped_defs = trueWith two identical unannotated functions, one in core.py and one in legacy.py, mypy core.py legacy.py reported only core.py:1: error: Function is missing a type annotation. The docs describe disallow_untyped_defs as disallowing “defining functions without type annotations or with incomplete type annotations.” Moving modules from the relaxed group into the strict one, a few at a time, is how a large codebase can adopt typing without a freeze on other work.
Speed and the cache
The same docs say mypy stores incremental cache information in .mypy_cache by default. On the two-file test project, a cold run after deleting the cache took 0.75 seconds and a warm run took 0.15 seconds. The numbers on a real project depend on its size, but the cache is what makes running mypy on every save practical. The folder belongs in .gitignore.
Third-party libraries need stubs
The first real run on most projects produces a different kind of error. A two-line script that imports PyYAML and calls yaml.safe_load() gave:
ex9.py:1: error: Library stubs not installed for "yaml" [import-untyped]
ex9.py:1: note: Hint: "python3 -m pip install types-PyYAML"
This is not a bug in the script. Many popular packages ship without type information, and their annotations live in separate stub packages. The mypy guide to running mypy describes typeshed as “the repository of types for the standard library and some 3rd party libraries,” and says the fix is to run the suggested pip command. It also mentions mypy --install-types to fetch every missing stub at once, with a warning that it is slower than installing stubs explicitly. Adding the stub packages to the project’s development requirements keeps every developer’s checker seeing the same types.
Getting started without a rewrite
A sensible order
The experiments suggest an order of work. Install mypy with pip install mypy and run it on the project as it is; expect few errors, because most functions are unannotated and skipped. Annotate function signatures at the boundaries first: functions that parse input, call external APIs or return None on failure. Those are where the str | None and TypedDict checks pay off. Avoid Any in return types unless the value really can be anything, and prefer object when the goal is to force a check. Once the first modules pass, run mypy in the same continuous integration job as the test suite, so a new type error blocks a merge the same way a failing test does. A checker that only runs when someone remembers it tends to drift back into a wall of ignored warnings.
What the annotations cost
Type hints cost nothing at runtime beyond storing the annotation, and they double as documentation that editors read for autocomplete. Their limit is the one this post opened with: Python will not stop a wrong type on its own. Code that must reject bad input at runtime, such as a web form handler, still needs explicit validation, and a separate library for that job, because mypy’s guarantees end where data from outside the program begins.
Sources
- Python documentation, “typing — Support for type hints”: https://docs.python.org/3/library/typing.html
- mypy 2.4.1 documentation, “Getting started”: https://mypy.readthedocs.io/en/stable/getting_started.html
- mypy 2.4.1 documentation, “Running mypy and managing imports”: https://mypy.readthedocs.io/en/stable/running_mypy.html
- mypy 2.4.1 documentation, “The mypy configuration file”: https://mypy.readthedocs.io/en/stable/config_file.html
