Sub topic 1
Type hints and what a type checker does
This chapter sets up the vocabulary for the rest of the tutorial. Generics only make sense once you know what a type checker does with an annotation and what Python itself ignores. Here you will see how a checker reads your code, where it stops, and which problem generics exist to solve.
Prerequisites
This chapter assumes you can:
- Write Python functions, classes, and methods.
- Read annotations such as
list[int]andstr | None. - Run a command-line tool such as
mypyorpyrighton a file. Both are static type checkers, and either works for every example here.
The examples use Python 3.12 or later. You do not need any generics knowledge yet.
What a type hint is
A type hint is an annotation that states which kind of value a name, parameter, or return value is meant to hold. Hints are ordinary Python syntax:
def total_price(prices: list[float], tax_rate: float = 0.2) -> float:
return sum(prices) * (1 + tax_rate)
count: int = 0
label: str | None = NonePython stores these annotations. It does not act on them. The interpreter treats the hints in the next example the same way, and the call still runs:
def double(n: int) -> int:
return n * 2
print(double("ab")) # prints abab; no error at runtimedouble("ab") works because "ab" * 2 is a valid string operation. The hint says int, but nothing at runtime checks it. The hint is a claim you make about your code, and a separate tool decides whether the claim holds.
What a static type checker does
A static type checker reads your source files without running them. It builds a model of the types in the program and reports places where the model contradicts itself. Examples are mypy, pyright, and the checkers built into editors.
For each expression, the checker works out a type. It takes the type from an annotation when one exists. Otherwise it infers the type from the code. It then verifies that every operation is allowed for the types involved.
The same source file goes to two independent consumers. The checker produces a report. The interpreter produces behavior. Neither depends on the other.
A first error
Save this as demo.py:
def double(n: int) -> int:
return n * 2
result = double("ab")Running mypy demo.py reports an error like this one:
demo.py:4: error: Argument 1 to "double" has incompatible type "str"; expected "int" [arg-type]The program is never run. The checker compares the argument type str with the parameter type int and finds a mismatch.
Inference: not every name needs a hint
A checker infers types from assignments and return statements, so you usually annotate function signatures and let it work out the locals:
from typing import reveal_type
def parse_ids(raw: str) -> list[int]:
parts = raw.split(",") # inferred: list[str]
ids = [int(p) for p in parts] # inferred: list[int]
reveal_type(ids)
return idsreveal_type is a debugging aid. A checker prints the type it has inferred at that point. At runtime, since Python 3.11, typing.reveal_type prints the type of the value and returns it unchanged, so the file still runs. Use it whenever you want to see what the checker believes.
Inference stops at function boundaries. A function with no annotations is treated as accepting and returning an unknown type. By default, mypy does not check the body of an unannotated function at all. Pyright infers return types from the body but cannot know the parameter types.
Any: the escape hatch
Any is a special type that is compatible with every other type in both directions. A value of type Any can be passed anywhere, and anything can be assigned to it. The checker stops checking operations on it.
from typing import Any
def load(path: str) -> Any:
...
data = load("config.json")
data.no_such_method() # no error: the checker trusts Any
count: int = data # no error eitherAny is useful at the edges of a program, such as parsed JSON. It is also contagious. One Any in a chain of calls can silently turn off checking for everything that depends on it. Missing annotations produce the same effect, so they are the most common source of Any in real code.
Narrowing
A checker follows control flow. Inside a branch, it can tighten a broad type into a narrower one. This is called narrowing.
def describe(value: int | str | None) -> str:
if value is None:
return "nothing"
if isinstance(value, int):
return f"number {value + 1}"
return f"text {value.upper()}"In the first if, value is None. After that branch returns, the checker knows value is int | str. After the isinstance branch, only str remains, so value.upper() is allowed. Without the checks, value.upper() would be an error, because int and None have no upper method.
The common narrowing forms are is None, isinstance, in tests against literal values, and truthiness checks. Narrowing is why you see type errors disappear when you add a guard.
Assignability
Most checker errors come down to one question: can a value of type A be used where type B is expected? This is called assignability. You will see the same question again when we reach variance.
For simple types, the rules are intuitive:
intis assignable toint.intis assignable toint | str, because the union accepts either.int | stris not assignable toint, because the value might be astr.- A subclass is assignable to its base class. A
boolcan go where anintis expected, becauseboolinherits fromint.
| Value type | Expected type | Allowed? | Reason | Column |
|---|---|---|---|---|
| `int` | `int \ | str` | Yes | The union includes `int` |
| `int \ | str` | `int` | No | The value might be a `str` |
| `bool` | `int` | Yes | `bool` is a subclass of `int` | |
| `list[int]` | `list[float]` | No | Containers raise a variance question, covered later | |
| anything | `Any` | Yes | `Any` accepts everything |
The list[int] row is worth noticing now. Even though int can be used where float is expected, a list of int cannot be used where a list of float is expected. The reason is that a list can be modified, and the chapter on variance explains it fully.
Why this leads to generics
Suppose you want a function that returns the first element of a list. The first attempt uses Any:
from typing import Any
def first(items: list[Any]) -> Any:
return items[0]
n = first([1, 2, 3])
n.upper() # no error from the checker, crashes at runtimeThe function works, but the checker has lost track of the type. The result is Any, so the mistake in n.upper() goes unnoticed. A second attempt lists every allowed type:
def first(items: list[int] | list[str]) -> int | str:
return items[0]
n = first([1, 2, 3])
n + 1 # error: n might be a strThis version is correct but unhelpful. The checker cannot tell that a list of int produces an int. The two unions are unrelated to each other.
What the function really needs to say is this: whatever element type goes in, that same type comes out. A generic function says exactly that. It introduces a type variable, which is a placeholder that the checker fills in separately for each call:
from collections.abc import Sequence
def first[T](items: Sequence[T]) -> T:
return items[0]
n = first([1, 2, 3]) # checker infers int
s = first(("a", "b")) # checker infers strHere T links the element type of the argument to the return type. The syntax is introduced properly in the next chapter. For now, notice that one definition serves many types and still gives the checker enough information to catch errors.
What the checker will not catch
A static checker works from annotations and inference. It cannot see values that exist only at runtime. Three things to keep in mind:
- Data from outside the program, such as JSON or user input, has only the type you declare for it. If you declare it wrongly, the checker believes you.
- Code that uses
Any, missing annotations, or# type: ignorecomments is partly or fully unchecked. - Annotations are not enforced when the program runs. A wrong call that the checker did not see will run, and may fail later with an unrelated error.
Summary of the working model
- Type hints are claims written in the source. Python stores them and does not enforce them.
- A static checker reads the source, infers types, and reports contradictions without running the program.
- Narrowing lets a checker tighten a broad type inside a branch.
Anydisables checking for the values it touches.- Generics let a definition tell the checker how types relate across a signature, so the checker does not fall back on
Anyor on lists of unrelated unions.
Exercise
A function is declared def shout(text: str) -> str: return text.upper(). A script calls shout(42) and runs it with plain python. A separate run of mypy on the same file is clean. What does each tool do, and what must have happened for mypy to be clean?
Show answer
Plain python runs the call and fails with an AttributeError, because int has no upper method. It does not report the annotation mismatch. Mypy would normally report an arg-type error for shout(42). A clean run means the checker did not see the bad call as a str-versus-int mismatch, for example because the call sits in an unannotated function that mypy skips, or the argument passed through a value of type Any.
Exercise
In the function below, why does the checker accept value.upper() in the last line, and what would happen if the isinstance branch were removed?
def f(value: int | str) -> str:
if isinstance(value, int):
return str(value)
return value.upper()
Show answer
After the isinstance(value, int) branch returns, the checker narrows value to str, which has an upper method. If the branch were removed, value would still be int | str and the checker would report an error, because int has no upper method.
Exercise
Why does def first(items: list[Any]) -> Any fail to give the checker useful information about the result, and what does a generic version add?
Show answer
The Any return type tells the checker nothing about the result, so it stops checking every use of it. A generic version declares a type variable T and writes Sequence[T] for the argument and T for the return type. This ties the returned type to the element type of the input, so a list of int gives an int.