Sub topic 14
What exists at runtime
This chapter assumes you can write generic functions and classes with the [T] syntax and that you run a checker such as mypy or pyright. Here you will see which generic information Python keeps when the program runs and which information only the checker uses.
Type arguments are not enforced
Python does not check type arguments when the program runs. Box[int]("text") runs without error, because Box[int] only builds a helper object and then calls Box.
from typing import get_args, get_origin
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'>
print(isinstance(b, Box)) # True
alias = Box[int]
print(get_origin(alias)) # <class '__main__.Box'>
print(get_args(alias)) # (<class 'int'>,)The instance b is a plain Box. Nothing in it records int. The same holds for functions: first[T] never receives T as a value, so the function body cannot ask what T is.
What does survive
Python keeps some metadata, and you can read it for tools such as serializers and validators.
Box.__type_params__is a tuple of the class's type parameters. Functions andtypealiases have the same attribute.Box[int]is a generic alias object.typing.get_originreturnsBoxfor it, andtyping.get_argsreturns(int,).- Each parameter is a
typing.TypeVarobject. It has__name__and, for the 3.12 syntax,__bound__,__constraints__, and__infer_variance__.
from collections.abc import Sized
def longest[T: Sized](a: T, b: T) -> T:
return a if len(a) >= len(b) else b
(t,) = longest.__type_params__
print(t.__name__) # T
print(t.__bound__) # <class 'collections.abc.Sized'>
print(t.__infer_variance__) # TrueThe bound is evaluated lazily, when you first read __bound__. For that reason you can refer to names defined later in the file.
Calling an alias such as Box[int](...) also sets __orig_class__ on the new instance. It is set after __init__ has finished, so __init__ cannot read it. It is also missing when you call Box(...) directly. Do not rely on it for program logic.
Checks that do not work
Because instances carry no type arguments, you cannot test for a parameterized type.
try:
isinstance(b, Box[int])
except TypeError:
print("cannot use a parameterized generic here")Use isinstance(b, Box) to test the class. To check the contents, inspect the values themselves, for example isinstance(b.value, int).
Type aliases
A type statement creates a TypeAliasType object. Its right-hand side is not evaluated until you read __value__.
type Pair[T] = tuple[T, T]
print(Pair.__type_params__) # (T,)
print(Pair.__value__) # tuple[T, T]
print(Pair[int]) # Pair[int]An alias is not a class. You cannot subclass it, and isinstance(x, Pair) raises TypeError.
Common errors
| Mistake | What happens |
|---|---|
| Expecting `Box[int]("x")` to raise | It runs. Only the checker reports it. |
| Using `isinstance(x, list[int])` | `TypeError` at runtime. |
| Reading `T` inside a function body as a value | In a 3.12 function, `T` is only visible in the signature and the body's scope as a type parameter. It does not hold the caller's type. |
| Relying on `__orig_class__` in `__init__` | Not set yet. |
Exercise
Given class Box[T]: ... and b = Box[str](42), does Python raise an error? What would type(b) print, and which tool reports the problem?
Show answer
Python raises no error. type(b) prints <class '__main__.Box'>, because instances do not store type arguments. A static type checker such as mypy or pyright reports that 42 is not a str.
Exercise
How can you list the type parameters of class Stack[T] at runtime, and why does isinstance(s, Stack[int]) fail?
Show answer
Read Stack.__type_params__, which gives (T,). isinstance(s, Stack[int]) raises TypeError because Stack[int] is a parameterized generic alias, and s has no record of int to compare against it.