Sub topic 4
How checkers infer types, and reveal_type
This chapter assumes you can annotate functions and run mypy or Pyright from the command line, as covered in the earlier chapters. It explains how a checker works out types you did not write, and how to look at them.
Inference fills in what you leave out
A checker does not need an annotation on every name. When you assign a value, it infers the variable's type from that value. You annotate function parameters and return types, and the checker infers most of the types inside the function body.
The checker reads the code in order. It sees items = [1, 2, 3], notes that every element is an int, and gives items the type list[int]. It sees name = "Ada" and gives name the type str. Later uses of these names are checked against those types.
Seeing the inferred type with reveal_type
reveal_type makes the checker print the type it inferred for an expression. It is the quickest way to find out why a checker accepts or rejects a line.
items = [1, 2, 3]
reveal_type(items)
name = "Ada"
reveal_type(name)Run mypy or pyright on this file. Both report list[int] for the first call and str for the second. The exact wording differs. mypy prints a note: line with Revealed type is "builtins.list[builtins.int]". Pyright prints an information: line with Type of "items" is "list[int]".
How the checker decides
The checker follows a small set of rules:
- If a name has a declared annotation, that declaration wins.
- If it has none, the checker infers the type from the first assignment.
- For a function call, it uses the function's declared return type.
- If the function has no return annotation, the result is treated as
Any, or the checker may infer the return type from the body. This depends on the tool and its settings.
The following diagram shows how a declared type and an inferred type feed into the same check.
Common surprises
Inference is based on what the checker can see, so it can be narrower than you intended. An empty list is a typical case:
values = []
values.append(1)
reveal_type(values)mypy may ask for an annotation here, with Need type annotation for "values". Pyright infers list[int] from the later append. Writing values: list[int] = [] removes the difference and states your intent.
Literal values are another case. Pyright keeps a narrow type for a declared constant, while for a plain variable it widens "Ada" to str. Use reveal_type when a result surprises you instead of guessing.
Exercise
You write count = 0 and then, later in the same function, count = "none". Which checker behavior explains the error, and what could you add to make the intent clear?
Show answer
The checker infers count as int from the first assignment, so assigning a str is reported as an incompatible type. If both types are intended, declare count: int | str = 0. If not, fix the second assignment.