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, and can run scripts. It also assumes you have seen the annotation syntax from the previous chapter. Here you learn what the interpreter does with those annotations. The short answer is that it stores them and does nothing else.
Hints are stored, not enforced
When Python runs a function definition, it evaluates each annotation and saves the result in the function's __annotations__ attribute. It never compares those annotations with the values you pass in.
def add(a: int, b: int) -> int:
return a + b
print(add.__annotations__)
print(add("x", "y")) # runs and prints xy; a static checker reports an error hereThe first line prints {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}. The second call passes strings, yet it runs and prints xy, because + works on strings. A static checker such as mypy or pyright would report the call as an error without running it.
Reading annotations at runtime
Because annotations are ordinary data, other code can read them. Tools such as dataclasses and validation libraries do exactly this.
def greet(name: str, times: int = 1) -> str:
return ", ".join([f"Hello, {name}"] * times)
for param, hint in greet.__annotations__.items():
print(param, "->", hint)The return key holds the return annotation. Module-level and class-level variable annotations are stored in the __annotations__ of the module or class. Local variables inside a function are not stored anywhere.
What happens with a wrong call
The error you see depends on what the function body does, not on the hint.
| Call | Annotation | Result at runtime |
|---|---|---|
| `add(1, 2)` | `int, int` | Returns `3` |
| `add("x", "y")` | `int, int` | Returns `"xy"` with no error |
| `add(1, "y")` | `int, int` | `TypeError` from `+`, not from the hint |
In the third row the TypeError comes from adding an int to a str. Removing the annotations would not change that.
Where the checking happens
Checking happens in a separate step that you run yourself, before the program runs. The checker reads your source, follows the annotations, and reports mismatches. The interpreter takes no part in it.
Common mistakes
- Expecting a hint to reject bad input. If you need a runtime check, write one with
isinstanceor use a validation library. - Trusting hints as proof. A program can pass the checker and still receive bad data from files, networks, or untyped code.
- Ignoring the checker. Without running mypy or pyright, hints work only as documentation.
Exercise
A function is declared as def double(n: int) -> int: return n * 2. What does double("ab") do when run with plain Python, and why?
Show answer
It returns "abab" with no error. The interpreter only stores the int annotation in __annotations__ and does not check it. String repetition with * is valid, so the body runs. Only a static checker such as mypy or pyright would report the call.