Skip to content

Python type hints: catch bugs before runtime (3.5+)

  • What Python does with type hints at runtime (almost nothing), and who checks them.
  • How to run mypy and pyright, and how a checker catches a None bug that tests missed.
  • The tools that carry most of the value: narrowing, Literal, TypedDict, Protocol, NewType and generics with the Python 3.12 syntax.
  • What changed in Python 3.14: annotations are evaluated lazily, so forward references need no quotes.
  • How to adopt typing gradually in an existing codebase, and the mistakes that make hints lie.

This page assumes you know the basic syntax (x: int, def f(a: str) -> bool, list[int], int | None). If not, start with Python type hints basics.

Type hints are annotations that describe the expected types of variables, parameters and return values. The syntax for function annotations arrived in Python 3.0 (PEP 3107); their meaning as types and the typing module arrived in Python 3.5 (PEP 484). The documentation is explicit: the Python runtime does not enforce function and variable type annotations. A static type checker such as mypy or pyright reads them and reports inconsistencies before the code runs, and editors use them for completion and refactoring. The rules that all checkers follow are collected in the typing specification.

In OrdersPortal, find_total() returns None when an order does not exist. A caller forgets that case. Every test uses an existing order, so the suite passes, and the bug waits for the first unknown order ID in production.

Running the samples: save each sample as a .py file and run it with Python 3.14 (python3 sample.py). To type-check, install the checkers into a virtual environment (python3 -m pip install mypy pyright) and run mypy sample.py and pyright sample.py. The outputs shown were produced with CPython 3.14.6, mypy 2.4.1 and pyright 1.1.414.

ORDERS = {"A-1001": 98.0, "A-1002": 19.5}
def find_total(order_id: str) -> float | None:
"""Return the order total, or None when the order does not exist."""
return ORDERS.get(order_id)
def total_with_tax(order_id: str) -> float:
return round(find_total(order_id) * 1.2, 2) # bug: None is not handled
print(total_with_tax("A-1001")) # the happy path works, so tests pass

Output of python3, mypy and pyright:

$ python3 s1_problem.py
117.6
$ mypy s1_problem.py
s1_problem.py:8: error: Unsupported operand types for * ("None" and "float") [operator]
s1_problem.py:8: note: Left operand is of type "float | None"
Found 1 error in 1 file (checked 1 source file)
$ pyright s1_problem.py
s1_problem.py:8:18 - error: Operator "*" not supported for "None" (reportOptionalOperand)
1 error, 0 warnings, 0 informations

Both checkers find the bug without running any code path. The fix is a check that the checker understands:

ORDERS = {"A-1001": 98.0, "A-1002": 19.5}
def find_total(order_id: str) -> float | None:
"""Return the order total, or None when the order does not exist."""
return ORDERS.get(order_id)
def total_with_tax(order_id: str) -> float:
total = find_total(order_id)
if total is None: # narrows float | None to float
raise KeyError(f"unknown order {order_id}")
return round(total * 1.2, 2)
print(total_with_tax("A-1001"))

Output: the script prints 117.6, mypy reports Success: no issues found in 1 source file and pyright reports 0 errors.

Python stores annotations so tools can read them, and otherwise ignores them. Since Python 3.14 (PEP 649 and PEP 749) it does not even evaluate them when a function or class is defined; they are computed on demand through the new annotationlib module.

from annotationlib import Format, get_annotations
def ship(order: Order, carrier: str = "post") -> Shipment:
return f"{order.id} via {carrier}"
class Order:
def __init__(self, order_id: str) -> None:
self.id = order_id
# 1. Annotations are not enforced: 42 is not a str, but this runs.
print(ship(Order("A-1001"), carrier=42))
# 2. In Python 3.14 annotations are evaluated lazily, so the forward
# reference to Order (defined later) needed no quotes. Shipment is never
# defined, which only matters if someone asks for the values.
print(get_annotations(ship, format=Format.STRING))
print(get_annotations(ship, format=Format.FORWARDREF))
try:
get_annotations(ship) # Format.VALUE is the default
except NameError as exc:
print("NameError:", exc)

Output (Python 3.14; the address varies):

A-1001 via 42
{'order': 'Order', 'carrier': 'str', 'return': 'Shipment'}
{'order': <class '__main__.Order'>, 'carrier': <class 'str'>, 'return': ForwardRef('Shipment', owner=<function ship at 0x7f2d02025a60>)}
NameError: name 'Shipment' is not defined

On Python 3.13 and earlier the same def line raises NameError: name 'Order' is not defined at definition time, which is why older code quotes forward references (order: "Order") or uses from __future__ import annotations (PEP 563). That future import still works unchanged in 3.14, but it is now deprecated and expected to be removed some time after Python 3.13 reaches end of life in 2029.

Libraries such as dataclasses and validation frameworks read annotations at runtime; that is the only way a hint changes behavior.

A checker infers a type for every expression and verifies each assignment, call and return against the declared types. A few rules explain most of its messages:

  • Narrowing. Inside if total is None: ..., isinstance() checks, match cases and early returns, the checker shrinks a union to the remaining possibilities. That is how the fix above satisfies it.
  • Any switches checking off. Unannotated parameters are treated as Any by default, and Any is compatible with everything in both directions. Use object when you mean “any value, but make me check before using it”.
  • Structural versus nominal. Classes are compatible by inheritance (nominal), while a Protocol matches any class with the right methods (structural, PEP 544).
  • Target version matters. Checkers validate syntax and stubs for one Python version. pyright infers it from the interpreter it finds: with python3 at 3.11 on the path, it rejected the 3.12 syntax below until run with --pythonversion 3.14.
Construct Use it for
int | None A value that may be missing (Optional[int] on older versions)
list[str], dict[str, int] Built-in generic containers
Literal["paid", "shipped"] A closed set of string or int values
TypedDict (with NotRequired, ReadOnly) The shape of a JSON-like dict
Protocol “Anything with a send() method”
NewType("OrderId", str) A distinct ID type that cannot be mixed up with other strings
def first[T](...), class Box[T], type X = ... Generics and aliases without TypeVar boilerplate
TypeIs, @override, Self Custom narrowing, safe overriding, fluent methods

The version that introduced each one is in Compatibility; constructs newer than your minimum Python version are available from the typing_extensions package; see typing_extensions.

The OrdersPortal orders module receives JSON payloads, turns them into Order objects and notifies billing about paid orders. Each hint encodes a rule that used to live only in comments: statuses are a closed set, order IDs are not interchangeable with SKUs, the payload has a known shape, and anything with a matching send() method can be a notifier. It uses 3.12 syntax, so it needs Python 3.12 or later.

from collections.abc import Iterable
from dataclasses import dataclass, field
from typing import Literal, NewType, Protocol, TypedDict, NotRequired
OrderId = NewType("OrderId", str)
type Status = Literal["pending", "paid", "shipped"] # Python 3.12+ alias
class OrderPayload(TypedDict):
"""Shape of the JSON body posted to /orders."""
id: str
status: Status
lines: list[tuple[str, int, float]]
coupon: NotRequired[str]
@dataclass
class Order:
id: OrderId
status: Status
lines: list[tuple[str, int, float]] = field(default_factory=list)
@property
def total(self) -> float:
return round(sum(qty * price for _, qty, price in self.lines), 2)
class Notifier(Protocol):
def send(self, to: str, message: str) -> None: ...
class ConsoleNotifier: # no inheritance needed
def send(self, to: str, message: str) -> None:
print(f"to {to}: {message}")
def parse_order(payload: OrderPayload) -> Order:
return Order(OrderId(payload["id"]), payload["status"], payload["lines"])
def first_or[T](items: Iterable[T], default: T) -> T: # Python 3.12+ generics
return next(iter(items), default)
def notify_paid(orders: Iterable[Order], notifier: Notifier) -> int:
paid = [o for o in orders if o.status == "paid"]
for order in paid:
notifier.send("billing@example.test", f"{order.id} paid {order.total:.2f}")
return len(paid)
if __name__ == "__main__":
payloads: list[OrderPayload] = [
{"id": "A-1001", "status": "paid", "lines": [("KB-101", 2, 49.0)]},
{"id": "A-1002", "status": "pending", "lines": [], "coupon": "SPRING"},
]
orders = [parse_order(p) for p in payloads]
print(notify_paid(orders, ConsoleNotifier()))
print(first_or((o.id for o in orders if o.status == "shipped"), OrderId("none")))

Saved as orders.py, it runs and passes mypy --strict and pyright with no errors:

$ python3 orders.py
to billing@example.test: A-1001 paid 98.00
1
none
$ mypy --strict orders.py
Success: no issues found in 1 source file
$ pyright --pythonversion 3.14 orders.py
0 errors, 0 warnings, 0 informations

Now four mistakes a caller might make. Python runs three of them silently; the protocol mismatch fails only when notify_paid reaches the call, as TypeError: EmailClient.send() missing 1 required positional argument: 'subject':

from orders import Order, OrderId, OrderPayload, first_or, notify_paid
class EmailClient:
def send(self, to: str, body: str, subject: str) -> None: ...
bad_payload: OrderPayload = {"id": "A-1003", "status": "refunded", "lines": []}
order = Order("A-1004", "paid")
notify_paid([order], EmailClient())
label: str = first_or([1, 2, 3], 0)

mypy reports each one:

$ mypy --strict callers.py
callers.py:6: error: Incompatible types (expression has type "Literal['refunded']", TypedDict item "status" has type "Literal['pending', 'paid', 'shipped']") [typeddict-item]
callers.py:7: error: Argument 1 to "Order" has incompatible type "str"; expected "OrderId" [arg-type]
callers.py:8: error: Argument 2 to "notify_paid" has incompatible type "EmailClient"; expected "Notifier" [arg-type]
callers.py:8: note: Following member(s) of "EmailClient" have conflicts:
callers.py:8: note: Expected:
callers.py:8: note: def send(self, to: str, message: str) -> None
callers.py:8: note: Got:
callers.py:8: note: def send(self, to: str, body: str, subject: str) -> None
callers.py:9: error: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
Found 4 errors in 1 file (checked 1 source file)

pyright reports the same four errors and, for the protocol, the reason: Parameter name mismatch: "message" versus "body" and Extra parameter "subject". Each error protects a rule: valid statuses, validated IDs, the notifier’s call signature, and a generic T solved as int.

Adopt gradually. Typing an existing codebase in one step rarely works. A sequence that does:

  1. Add a checker to CI in its default (lenient) mode, so unannotated code is not checked and only real inconsistencies fail the build.
  2. Annotate the boundaries first: public functions, data models, anything that parses external input. These give the most value per line.
  3. Turn on strict mode per package as it becomes clean (mypy --strict, or per-module options in pyproject.toml; "strict" paths in pyright’s configuration), so new code cannot regress.
  4. Treat # type: ignore[code] and cast() as debt: always include the error code and a reason. A bare # type: ignore hides every error on the line, including future ones.

Validate at the boundary, trust inside. Hints describe what the code assumes. Request JSON, database rows or CSV files can contain anything, so check them once where they enter the system, then let the checker carry the guarantee inward.

Use reveal_type(expr) (built into typing since 3.11 and understood by both checkers) when a checker’s message surprises you; it prints the inferred type during checking.

  • Expecting runtime enforcement. ship(order, carrier=42) runs. If a value comes from outside, validate it.
  • Leaving parameters unannotated in “typed” code. They become Any, and everything that flows from them is unchecked. mypy --strict reports them.
  • Using Any where object is meant. Any silences errors; object forces a check before use.
  • Annotating mutable containers too precisely or too loosely. list[int] is invariant: a list[bool] is not accepted where list[int] is expected because the callee could append an int. Accept Sequence[int] or Iterable[int] for read-only parameters.
  • Checking against the wrong Python version. Set python_version (mypy) or pythonVersion (pyright) to your minimum supported version.

Type hints pay off most in long-lived, shared code and least in throwaway scripts.

Situation Recommendation
Library or service code maintained by a team Annotate everything public; run a checker in CI, strict for new packages
Data crossing a boundary (API, file, DB) TypedDict or dataclasses plus runtime validation at entry
Duck-typed collaborators (notifiers, repositories) Protocol instead of base classes
Heavy metaprogramming, dynamic attributes Annotate the public surface; accept Any inside, with tests
One-off script or exploratory notebook Optional; annotate only function signatures if it grows
Code that must run on several Python versions Use syntax for your oldest version, or typing_extensions
Python Typing milestone
3.0 Function annotation syntax (PEP 3107)
3.5 typing module and type hint semantics (PEP 484)
3.6 Variable annotations (PEP 526)
3.7 from __future__ import annotations (PEP 563)
3.8 Protocol, TypedDict, Literal, Final
3.9 list[int] and other built-in generics (PEP 585), Annotated
3.10 X | Y unions (PEP 604), ParamSpec, TypeGuard
3.11 Self, NotRequired, LiteralString, reveal_type, assert_never
3.12 Type parameter syntax and type statement (PEP 695), @override
3.13 Type parameter defaults, TypeIs, ReadOnly, warnings.deprecated
3.14 Lazy annotations and annotationlib (PEP 649/749); Union[int, str] and int | str now create the same runtime type

1. Does Python check type hints at runtime? No. The interpreter stores annotations (lazily, since 3.14) but does not enforce them. Static checkers such as mypy and pyright check them before running; some libraries, such as dataclasses or validation frameworks, read them at runtime and act on them.

2. What is the difference between Any and object? Both accept any value. Any also lets you do anything with the value and is assignable to every type, so it switches checking off. object only allows operations that every object supports, so you must narrow (for example with isinstance) before using it.

3. When would you use a Protocol instead of an abstract base class? When you care that an object has certain methods, not where it comes from: third-party classes, test fakes or simple callables can satisfy a protocol without inheriting from anything. An ABC is better when you want shared implementation or runtime isinstance checks against a registered hierarchy.

4. Why is list[bool] not accepted where list[int] is expected, even though bool is a subclass of int? Lists are mutable, so their type parameter is invariant: the callee could append a plain int to what the caller believes is a list of bool. For read-only parameters, accept Sequence[int], which is covariant.

5. Senior scenario: you inherit a 200,000-line untyped service with frequent None-related production errors. How do you introduce typing without stopping feature work? Add mypy or pyright to CI in lenient mode first, with a baseline so existing errors do not block merges but new ones do. Annotate the highest-traffic boundaries (request parsing, data models, repository functions) and run those packages in strict mode first, so no Any hides an unchecked None, since None bugs are the stated pain. Enforce strict mode for new modules and promote old packages as they become clean, tracking the count of type: ignore and Any as metrics. Pair it with runtime validation at external inputs, because hints cannot prevent bad data from arriving.

  • Type hints describe intent; Python stores them but does not enforce them. Run mypy or pyright to get value from them.
  • Narrowing, Literal, TypedDict, Protocol, NewType and generics turn implicit rules into checked ones.
  • Python 3.14 evaluates annotations lazily; quotes and from __future__ import annotations are no longer needed for forward references in 3.14-only code.
  • Adopt gradually: boundaries first, strict mode per package, validation at system edges.
  • Configure the checker for your minimum Python version, and use typing_extensions for newer features.