Sub topic 2
Annotating functions and variables
This chapter assumes you can write Python 3.10+ functions and classes, run the command line, and have mypy or Pyright installed in a virtual environment. Annotations are the input every checker works from. Once you can write them, the later chapters on inference, unions, and generics build directly on them.
What an annotation is
An annotation is a piece of syntax that attaches a type expression to a parameter, a return value, or a variable. Python stores it but does not enforce it. Only a static checker reads it as a rule.
def double(x: int) -> int:
return x * 2
print(double("ab")) # runs and prints "abab"; the checker reports an errorAt runtime, double("ab") succeeds because "ab" * 2 is valid. mypy and Pyright report that "ab" is not an int before the program runs. The annotations are available at runtime as double.__annotations__, which is how libraries such as pydantic and FastAPI use them. The interpreter itself never checks them.
Function annotations
Annotate each parameter with name: type and the return value with -> type. Together these form the function's signature, which is the part callers rely on.
def area(width: float, height: float) -> float:
return width * height
def log(message: str) -> None:
print(message)A function that returns nothing is annotated -> None. Leaving the return annotation off is different from writing -> None: the first tells the checker nothing, and the second declares that the function returns nothing useful. If you declare -> None and then use the result, for example x = log("hi") followed by x.upper(), the checker flags it.
Defaults go after the annotation, with spaces around =:
def connect(host: str, port: int = 5432, timeout: float = 3.0) -> None: ...Variable-length arguments
For *args and **kwargs, the annotation describes each individual item, not the whole collection.
def log_all(prefix: str, *parts: int, **options: bool) -> None:
# parts is tuple[int, ...]; options is dict[str, bool]
print(prefix, parts, options)Callables
Use Callable from collections.abc for function arguments. The first part lists the parameter types, and the second is the return type.
from collections.abc import Callable
def apply(func: Callable[[int], str], value: int) -> str:
return func(value)
print(apply(str, 7))Variable annotations
Write name: type before or together with an assignment. Since Python 3.9 the built-in collections accept subscripts directly, so you no longer need typing.List or typing.Dict.
count: int = 0
names: list[str] = []
scores: dict[str, int] = {}
point: tuple[int, int] = (3, 4)
coords: tuple[float, ...] = (1.0, 2.0, 3.0)
pending: str # declared only; no value yetThe two tuple forms differ. tuple[int, int] is exactly two integers. tuple[float, ...] is any number of floats.
A variable usually does not need an annotation when you assign a value, because the checker infers it. Annotate when the inferred type would be too narrow. The classic case is an empty container: names = [] gives the checker nothing to infer from, and mypy asks you for an annotation.
| Situation | Annotate? | Reason |
|---|---|---|
| Function parameters and returns | Yes | Checkers do not infer these from the body |
| `x = 5` | Usually no | Inferred as `int` |
| `items = []` or `{}` | Yes | No elements to infer from |
| Declared now, assigned later | Yes | Nothing to infer yet |
| Public module or class attributes | Often | Documents the intended type |
Class attributes
Annotations in a class body declare instance attributes. Two helpers refine them.
from typing import ClassVar, Final
MAX_RETRIES: Final = 3
class Counter:
registry: ClassVar[dict[str, int]] = {}
step: int
def __init__(self, step: int = 1) -> None:
self.step = step
self.total = 0 # inferred as int from the assignment
c = Counter(2)
print(c.step, c.total, Counter.registry, MAX_RETRIES)ClassVar[...]marks an attribute as belonging to the class, so assigning through an instance is an error.Finalmarks a name that must not be reassigned. With a value, the checker infers the type, soFinal = 3isint.__init__is annotated-> None. If every parameter other thanselfis annotated, mypy accepts the omission, but writing it is clearer.selfandclsneed no annotation.
Unannotated code is not the same as `Any`-typed code
A function with no annotations at all is "untyped" to a checker, and the two tools treat it differently.
def add(a, b):
return a + b
result: int = add("x", "y")
print(result)By default mypy skips the bodies of untyped functions and treats their return value as Any, so it reports nothing here even though the program stores a string in an int variable. Pyright analyzes the body and infers types from it, so it can catch more. Adding even one annotation to a function makes mypy check its body. The setting check_untyped_defs changes this, and the configuration chapter covers it.
Common errors
- Using
Noneas a default for a non-optional type.def f(x: int = None)is an error in current mypy and in Pyright, becauseNoneis not anint. Writex: int | None = None. The next chapters explain unions. - Using a mutable literal in the wrong place.
items: list[int] = []is fine as a local variable. As a class attribute shared by all instances, it needsClassVaror should be set in__init__. - Writing
listwithout parameters. A barelistis treated aslist[Any]and hides mistakes. Preferlist[int]. - Forgetting the return annotation on one function in a typed module. Callers then receive
Anyfrom that function. - Annotating
self.xin a method but not declaring it in the class body. This works, but declaring it once makes the intent clearer.
Checking your work
Run a small file through both tools:
mypy example.py
pyright example.pyFor the double("ab") call above, mypy reports that the argument has type str but int was expected. Pyright reports the same mismatch under its own wording. Both exit with a non-zero status, so a script or CI job can detect the failure.
Exercise
This function is unannotated: def total(prices, tax=0.2): return sum(prices) * (1 + tax). It takes a list of floats and a float rate, and returns a float. Write the annotated version. Then explain why prices = [] inside another function would need its own annotation but rate = 0.2 would not.
Show answer
def total(prices: list[float], tax: float = 0.2) -> float: return sum(prices) * (1 + tax). For prices = [], the checker sees no elements, so it cannot infer the element type and mypy asks for an annotation such as prices: list[float] = []. For rate = 0.2, the checker infers float from the value.
Exercise
A class declares limit: ClassVar[int] = 10. What does the checker do with obj.limit = 20 on an instance, and what does it do with Counter.limit = 20?
Show answer
It reports an error for the instance assignment, because a ClassVar can be set only through the class. The class assignment Counter.limit = 20 is accepted, since 20 is an int.