Sub topic 14
What exists at runtime
This chapter covers what Python keeps of a generic definition when the program runs, and what only a static type checker sees. It assumes you can read def f[T] and class C[T], know that mypy or pyright check annotations without running the program, and have seen list[int] in annotations. The examples need Python 3.12 or later.
The central rule: the interpreter does not check type arguments
A type checker reads your source and reasons about it. The interpreter executes it. Generics are a contract for the first reader. The second reader mostly ignores them.
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
b = Box[int]("text") # a type checker reports an error here
print(type(b)) # <class '__main__.Box'>; no runtime check is made
print(b.value) # textA checker rejects the call because "text" is not an int. At runtime the call succeeds, since Box[int] is only a handle that creates an ordinary Box. The object b is an instance of Box. It is not an instance of a special "box of int" class.
This design is called type erasure in other languages, but Python's version is partial. Some generic information survives as ordinary objects you can inspect. The sections below separate what survives from what does not.
What survives: type parameter objects
Every generic class, function, and type alias created with the Python 3.12 syntax records its parameters in a __type_params__ tuple.
from typing import get_args, get_origin
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def first[T](items: list[T]) -> T:
return items[0]
print(Box.__type_params__) # (T,)
print(first.__type_params__) # (T,)
t = Box.__type_params__[0]
print(type(t)) # <class 'typing.TypeVar'>
print(t.__name__) # T
print(t.__infer_variance__) # TrueEach T is a real typing.TypeVar object. It has a name, a bound, constraints, and variance flags. For a TypeVar created by the new syntax, __infer_variance__ is True. That flag tells a checker to work out variance from how the class uses T. The runtime itself never uses the flag.
Python does not give Box a special metaclass. A generic class still has type as its class. In 3.12 and later, class Box[T] implicitly adds Generic to the base classes, which is why Box[int] works at all.
What survives: parameterized aliases
Subscripting a generic class returns an alias object that remembers the class and the arguments.
alias = Box[int]
print(alias) # __main__.Box[int]
print(get_origin(alias) is Box) # True
print(get_args(alias)) # (<class 'int'>,)
b = alias(3)
print(type(b) is Box) # True
print(b.__orig_class__) # __main__.Box[int]Use typing.get_origin and typing.get_args instead of reading __origin__ and __args__ directly. They also handle built-in generics such as list[int], whose alias type is types.GenericAlias.
The call alias(3) does two things:
- It creates a plain
Boxby calling the origin class. - It then tries to store the alias on the new instance as
__orig_class__.
The second step is best effort. It happens after __init__ finishes, so self.__orig_class__ does not exist inside __init__. It also fails silently when the instance cannot take new attributes, for example when the class defines __slots__. And it only happens when the caller wrote Box[int](3). A plain Box(3) never records an argument, because the interpreter does not infer T from the value. Treat __orig_class__ as a debugging aid and never rely on it.
What does not survive: the type arguments of an instance
An instance does not know what T was bound to. Two consequences follow.
You cannot test against a parameterized generic. isinstance accepts the bare class and rejects the subscripted form:
b = Box(1)
print(isinstance(b, Box)) # True
try:
isinstance(b, Box[int])
except TypeError as e:
print(e) # isinstance() argument 2 cannot be a parameterized genericThe interpreter refuses the call because it cannot answer it. A Box holding 1 and a Box holding "x" have the same class.
You cannot use T as a value. Inside Box, the name T exists as a TypeVar object, but it is not a class. T(), isinstance(x, T), and T.__name__ as a way to find the real argument all fail or give meaningless results. In Python 3.12 and later, the name T is not even visible outside the scope that declares it, as the scoping chapter explained.
Working around erasure: pass the type as a value
When code needs the type at runtime, pass it as an ordinary argument. A class is a value, so you can pass it and also let the checker relate it to T through type[T].
def only[T](items: list[object], kind: type[T]) -> list[T]:
return [x for x in items if isinstance(x, kind)]
print(only([1, "a", 2, 3.5], int)) # [1, 2]Here the checker infers list[int] for the result, and the runtime test uses the real class int. The parameter kind carries the information that erasure removed from T.
A callable works too, and it is the more flexible choice when the target type is a constructor:
from collections.abc import Callable
def convert[T](kind: Callable[[str], T], raw: str) -> T:
return kind(raw)
n = convert(int, "42") # checker infers int
x = convert(float, "2.5") # checker infers floatThe same idea appears in dataclass-like and validation libraries. Some of them, such as pydantic, go further. Subscripting a generic model there creates a new real subclass, so the parameter becomes a runtime fact. That is a library feature built on top of Python. The language does not do it for you.
Lazy evaluation of bounds and aliases
The new syntax delays evaluation of some expressions until someone asks for them. The interpreter does not evaluate these at the point of definition:
- the bound and constraints of a type parameter
- the value of a
typealias
def pick[T: Later](x: T) -> T:
return x
class Later: ...
print(pick.__type_params__[0].__bound__) # <class '__main__.Later'>
type Json = dict[str, Json] | list[Json] | str | int | float | bool | None
print(Json.__name__) # Json
print(Json.__value__) # dict[str, Json] | list[Json] | str | int | float | bool | NoneLater is defined after pick, yet the code runs, because __bound__ is evaluated on first access. The recursive Json alias works for the same reason: its right-hand side is evaluated only when you read __value__. If the bound named something that never gets defined, the error would appear at that first access, not at definition time.
A type statement produces a typing.TypeAliasType object. It is not the same as a plain assignment such as Pair = tuple[int, int], which just binds a name to a types.GenericAlias. The practical differences:
Jsonis a distinct object with a name and a__value__.isinstance(x, Json)raisesTypeError, because an alias is not a class.- Subscripting a generic alias, as in
Pair[int], gives atypes.GenericAliasthat records the alias and the argument.
Annotations are data too
Annotations are stored on the function or class, and the checker's view of them is available to your code. In Python 3.12 and 3.13, annotations are evaluated when the def statement runs unless the module has from __future__ import annotations. Python 3.14 evaluates them lazily by default. In every version, use typing.get_type_hints to resolve them, since it handles strings and forward references:
import typing
def first[T](items: list[T]) -> T:
return items[0]
hints = typing.get_type_hints(first)
print(hints["return"]) # ~T or T, depending on how the TypeVar prints
print(hints["items"]) # list[T]Frameworks use this to build behavior from annotations, for example dependency injection or validation. Those tools read the annotations at runtime and act on them, but the interpreter itself never enforces them.
Summary table
| Item | Exists at runtime? | Enforced by the interpreter? |
|---|---|---|
| `T` as a `TypeVar` object in `__type_params__` | Yes | No |
| Bound and constraints of `T` | Yes, evaluated lazily | No |
| Variance flags such as `__infer_variance__` | Yes, as data | No |
| `Box[int]` alias with origin and arguments | Yes | No |
| Type argument of a given instance | No, except best-effort `__orig_class__` | No |
| `isinstance(x, Box[int])` | Raises `TypeError` | Not allowed |
| Value of a `type` alias | Yes, through `__value__` | No |
| Annotations on functions and classes | Yes, as data | No |
Common mistakes
- Expecting a runtime error from a wrong type argument.
Box[int]("text")runs. Only the checker complains. Run the checker in CI to get the benefit. - Using
isinstancewith a subscripted generic. Test against the bare class, then inspect contents yourself if you must. - Treating
Tas a class. It is a type variable, so it cannot be called or used inisinstance. Pass atype[T]parameter if you need the class. - Relying on definition-time evaluation of bounds. With the new syntax, a bad bound surfaces only on first access to
__bound__, so a checker catches it earlier than a test run would.
Exercise
Predict the output of this program, and say which line a type checker would reject. class Cell[T]: def _init(self, value: T) -> None: self.value = value c = Cell[int]("x") print(type(c) is Cell) print(c.origclass__) try: isinstance(c, Cell[int]) except TypeError: print("error")
Show answer
The checker rejects the line c = Cell[int]("x"), because "x" is not an int. At runtime that line succeeds. The program prints True, because c is a plain Cell. It then prints __main__.Cell[int], since Cell[int]("x") stores the alias on the instance after construction. Finally it prints error, because isinstance rejects a parameterized generic with a TypeError.
Exercise
Write count_of[T](items: list[object], kind: type[T]) -> int that returns how many items are instances of kind. Why can it not take T alone, without the kind parameter?
Show answer
def count_of[T](items: list[object], kind: type[T]) -> int: return sum(1 for x in items if isinstance(x, kind)). The T in the signature is erased, so the function body has no class to test against. Passing kind supplies the class as a runtime value, and type[T] still lets the checker relate it to T.