Sub topic 4
How checkers infer types, and reveal_type
This chapter assumes you can run mypy and Pyright on a directory and read their error output, as covered in the previous chapter. It also assumes you know how to annotate function parameters and return values. You need Python 3.10 or newer.
Annotating every variable would be tedious. Checkers fill most gaps by inference, which means working out a type from the surrounding code. This chapter covers where inference gets its information, how to see its result with reveal_type, and the places where mypy and Pyright reach different answers.
Where inferred types come from
A checker builds the type of an expression from several sources:
- The literal value on the right of an assignment, such as
3,"Ada"or[1, 2, 3]. - The declared return type of any function or method being called.
- The declared types of parameters and attributes.
- Narrowing from earlier checks such as
is Noneorisinstance.
Inference never uses runtime values. The checker reads the program text and nothing else. A variable assigned 3 is an int to the checker because the literal is an int, not because the program ran.
Asking the checker with reveal_type
reveal_type makes the checker print the type it inferred for an expression. It is the main debugging tool for inference problems.
items = [1, 2, 3]
reveal_type(items)
name = "Ada"
reveal_type(name)Run both tools on this file and the output differs in format:
| Tool | Output for `items` |
|---|---|
| mypy | `note: Revealed type is "builtins.list[builtins.int]"` |
| Pyright | `information: Type of "items" is "list[int]"` |
mypy prints fully qualified names such as builtins.int. Pyright prints short names. Both report the same type.
reveal_type is not a normal function from the checker's side. Both tools recognize the name without an import. At runtime it behaves differently depending on your Python version:
- On Python 3.11 and newer,
typing.reveal_typeexists. It prints the type of its argument to stderr and returns the argument unchanged. - On Python 3.10, calling
reveal_typewithout an import raisesNameErrorwhen the program runs. Import it withfrom typing_extensions import reveal_typeif you want the line to run.
Declared type versus narrowed type
A variable can have a declared type that is wider than the type the checker knows at a given line. When you assign to it, both tools narrow it to the type of the assigned value.
value: int | str = 3
reveal_type(value) # int
value = "x"
reveal_type(value) # strWithout the annotation, the variable's declared type would come from the first assignment. In mypy, value = 3 followed by value = "x" is an error, because value is an int. Pyright infers the declared type of an unannotated variable as the union of all assigned types, so it accepts both assignments. When you want a variable to hold several types, write the annotation.
Empty containers
An empty list literal gives the checker no element type to work from.
names = []
names.append("Ada")
reveal_type(names)mypy handles this case by looking at later statements in the same scope. It sees the append call and settles on list[str]. If it cannot find such a statement, it reports Need type annotation for "names". Pyright does not look ahead. It infers list[Unknown] and, in strict mode, reports the unknown type.
Annotate empty containers and the problem goes away:
names: list[str] = []
scores: dict[str, int] = {}Mixed collections
When a list holds values of different types, the tools disagree.
mixed = [1, "a"]
reveal_type(mixed)- mypy joins the element types to their closest common base class and reports
list[object]. - Pyright keeps the union and reports
list[int | str].
The object result from mypy often causes confusing errors later, because object has almost no methods. If you meant a union, annotate it: mixed: list[int | str] = [1, "a"].
Inferring return types
Here the two tools differ most. Consider a function with an annotated parameter and no return annotation.
def double(x: int):
return x * 2
reveal_type(double(2))- Pyright infers the return type from the body and reveals
int. - mypy treats a missing return annotation as
Anyand revealsAny. It does not read the body to guess.
The rule behind the mypy result: a function with at least one annotation counts as annotated, and anything it leaves out defaults to Any. A function with no annotations at all is untyped. By default mypy skips checking the body of an untyped function, so errors inside it go unreported. The option --check-untyped-defs turns that checking on.
Write return annotations on public functions. This gives the same result in both tools and documents the contract. Inference is best used for local variables inside a function body.
Reading unexpected results
When an error message mentions a type you did not expect, follow these steps:
- Put
reveal_type(expr)on the line before the error, using the exact expression the message names. - Compare the printed type with what you intended.
- Look for the cause: an empty container, a missing return annotation, a mixed collection, or a value that came from an unannotated function and is therefore
Any. - Fix it with an annotation at the source, not at the line where the error appeared.
A reveal_type result of Any in mypy, or Unknown in Pyright, means the checker has lost track of the type. Later operations on that value are not checked. Both words signal a gap that annotations should close, and the next chapters on gradual typing cover this in more detail.
Summary of the differences
| Situation | mypy | Pyright | Column |
|---|---|---|---|
| Output format | Qualified names, `Revealed type is` | Short names, `Type of "x" is` | |
| `x = 3` then `x = "a"` | Error: incompatible assignment | Accepted, declared type is a union | |
| `[]` then `.append("a")` | Infers `list[str]` in the same scope | `list[Unknown]` | |
| `[1, "a"]` | `list[object]` | `list[int \ | str]` |
| Unannotated return type | `Any` | Inferred from the body |
Exercise
You run mypy and Pyright on def f(x: int): return [x, "a"] followed by reveal_type(f(1)). What does each tool report for the call, and how would you make both report the same type?
Show answer
mypy reports Any, because the function has no return annotation and mypy does not infer return types from the body. Pyright infers the body and reports list[int | str]. Add an explicit return annotation, def f(x: int) -> list[int | str]:, and both tools report list[int | str].
Exercise
Why does reveal_type(items) crash with a NameError when you run a script on Python 3.10, and what is the fix?
Show answer
Before Python 3.11, reveal_type is not a builtin or part of typing. The checkers recognize the name specially, but the interpreter does not. Import it with from typing_extensions import reveal_type, or remove the call before running the code.