Sub topic 2
What hints do and do not do at runtime
This chapter assumes you can write Python functions and classes, know the built-in types (int, str, list, dict, tuple), and can run scripts and install packages with pip. It also assumes you have seen the annotation syntax name: type, -> type, and name: type = value.
The interpreter stores hints and does not check them
When Python runs a def statement, it evaluates each annotation and saves the result on the function object. It never compares those values with the arguments you pass. The annotations are metadata for tools.
def add(a: int, b: int) -> int:
return a + b
print(add.__annotations__)
print(add(1, 2))
print(add("x", "y"))The output is:
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
3
xyThe call add("x", "y") succeeds because + works on strings. A static checker such as mypy or pyright reports this call as an error, but only when you run the checker. Python itself raises no error.
The return annotation is stored under the key "return". Parameters without an annotation do not appear in the dictionary.
Where annotations are stored
Where Python stores an annotation depends on where you write it.
| Location | Stored in | Evaluated when |
|---|---|---|
| Function parameters and return | `func.__annotations__` | When `def` runs (see the next section for newer versions) |
| Class body variables | `ClassName.__annotations__` | When the class body runs |
| Module-level variables | the module's `__annotations__` | When the module runs |
| Local variables inside a function | Nowhere | Never |
An annotation on a variable does not create the variable unless you also assign a value.
count: int
print(__annotations__)
try:
print(count)
except NameError as error:
print("NameError:", error)The first print shows {'count': <class 'int'>}. The second shows a NameError, because count: int records the hint but binds no value. This is useful in class bodies, where you can declare an attribute's type without giving it a default.
Annotations are real expressions
Before Python 3.14, the interpreter evaluated annotation expressions at definition time. A misspelled or undefined name in an annotation therefore failed immediately:
try:
def broken(x: Undefined) -> None:
pass
except NameError as error:
print("NameError:", error)On Python 3.13 and earlier this prints NameError: name 'Undefined' is not defined. Python 3.14 evaluates annotations lazily, so the same code no longer fails when the function is defined. The error appears only if something reads the annotation. A later chapter covers forward references and postponed evaluation, which is how older versions defer this work.
Evaluation at definition time has two practical consequences:
- An annotation that costs a lot to compute, or that imports a heavy module, slows down import time.
- An annotation can fail at runtime even though the function body would never use that name.
Reading hints at runtime
Reading __annotations__ directly gives the raw stored objects. When an annotation is a string, such as "int" or a forward reference, the raw dictionary holds the string. Use typing.get_type_hints to resolve strings into real types:
from typing import get_type_hints
def find(user_id: int, names: dict[int, str]) -> str | None:
return names.get(user_id)
print(get_type_hints(find))On Python 3.10 and later, str | None is a real runtime expression. On Python 3.9 and earlier it raises TypeError when the def runs, unless you postpone evaluation. The checker accepts the syntax in either case, so check which Python version your project actually runs.
For finer control, inspect.signature(func) gives you the parameters, their defaults, and their annotations together.
Enforcing hints yourself
Since Python ignores hints, runtime checking exists only when some code reads the annotations and acts on them. Libraries such as pydantic and beartype do this. You can see the principle in a minimal decorator:
import functools
import inspect
from typing import get_type_hints
def enforce(func):
hints = get_type_hints(func)
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for name, value in bound.arguments.items():
expected = hints.get(name)
if isinstance(expected, type) and not isinstance(value, expected):
raise TypeError(
f"{name} must be {expected.__name__}, got {type(value).__name__}"
)
return func(*args, **kwargs)
return wrapper
@enforce
def add(a: int, b: int) -> int:
return a + b
print(add(1, 2))
try:
add("x", "y")
except TypeError as error:
print(error)This prints 3 and then a must be int, got str. The sketch handles only plain classes. It skips list[int], unions, and other generic forms, and it ignores the return value. It also inherits Python's own rules: True passes an int check because bool is a subclass of int. Production libraries handle these cases, and they add per-call overhead that a static checker does not have.
Who reads the hints
Static checkers parse the source text and never import or run your program. That is why they can flag code on a path that never executes in a test. It is also why they cannot see values that exist only at runtime.
Common mistakes
- Expecting a
TypeErrorfrom a wrong argument. The error you see is whatever the function body raises, if any. If the body happens to work, the wrong type goes through silently. - Treating a passing test as proof that hints are correct. Hints and tests can disagree without either failing.
- Annotating
x: int = "a"and expecting an error when you run the file. Only the checker complains. - Reading
__annotations__on a function and assuming every value is a class. Values can be strings, unions, or generic aliases. - Writing a hint that depends on a name defined later in the file, which breaks on Python 3.13 and earlier.
Exercise
A function is declared as def double(n: int) -> int: return n * 2. You call double("ab") and the program prints abab without an error. Explain why, and name two ways to get a failure for this call.
Show answer
Python stores the annotations but does not check them. The string "ab" supports * with an integer, so the body runs and returns "abab". To get a failure, run a static checker such as mypy or pyright, which reports the argument type mismatch before the program runs. Alternatively, add runtime enforcement that reads the annotations, such as a decorator built on get_type_hints or a library like pydantic or beartype.
Exercise
What does this script print, and why? value: int followed by print(value).
Show answer
It raises NameError, because value: int records an annotation but does not assign a value, so no variable named value exists. The annotation is stored in the module's __annotations__, which is a separate place from the variables.