Sub topic 13
Scoping and lazy evaluation of type parameters
This chapter assumes you can read the def f[T] and class C[T] syntax from the earlier chapters. It also assumes you know that ordinary annotations are normally evaluated when a def statement runs. Here you will see where a type parameter name is visible. You will also see which parts of a generic definition Python evaluates later than the rest.
Where a type parameter name lives
When you write def first[T](items: list[T]) -> T, Python creates a hidden scope for T. This is an annotation scope. It sits between the surrounding scope (module, class, or function) and the function or class you are defining.
The name T is visible in three places:
- the annotations of the function or class
- the bounds, constraints, and defaults of the type parameters
- the body of the function, or the body of the class and its methods
It is not visible anywhere else:
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
print([p.__name__ for p in Stack.__type_params__]) # ['T']
try:
print(T)
except NameError as error:
print(error) # name 'T' is not definedT is not a module-level variable and not a class attribute, so Stack.T also fails. The runtime object that represents the parameter is reachable through __type_params__. Generic functions, classes, and type aliases all have this attribute. Non-generic ones have an empty tuple.
With the older style, T = TypeVar("T") creates a module-level variable. It leaks into every scope, and two unrelated functions can share one T by accident. The new syntax removes that coupling. Each generic definition declares its own parameters.
Nesting and shadowing
A method of a generic class sees the class's parameters without redeclaring them:
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
def pair_with[U](self, other: U) -> tuple[T, U]:
return (self.value, other)pair_with uses T from the class and adds its own U. Within the signature of pair_with, T is bound to the whole instance and U is solved per call.
Two rules keep names unambiguous:
- Declaring the same name twice in one list, as in
def f[T, T](), is aSyntaxError. - A type parameter shadows any outer name with the same spelling, including builtins.
def broken[str](x: str) -> str: # here "str" is the type parameter, not the builtin
return xThis is legal Python, but a checker will treat str as an unconstrained type variable. Avoid reusing the name of a type parameter in a nested generic scope. Type checkers report that as an error even where the runtime accepts it.
Class scope is visible, with one difference
A function body cannot see names defined directly in an enclosing class body. That is the usual Python rule. An annotation scope inside a class is the exception: it can see the class's names. Bounds and annotations can therefore refer to a class attribute without qualifying it:
class Registry:
class Handler:
pass
def register[H: Handler](self, handler: H) -> H:
return handler
print(Registry.register.__type_params__[0].__bound__)
# <class '__main__.Registry.Handler'>Handler here is written as a bare name, yet it resolves. The lookup order inside the annotation scope is: the type parameters, then the enclosing class body, then the module, then builtins.
The body of register is different. Code inside it follows the normal function rule, so it sees H but would need Registry.Handler to name the class.
What is evaluated lazily
Python evaluates a def or class statement top to bottom. Most parts of it run immediately. The new syntax defers some parts until something asks for them.
| Part of the definition | When it is evaluated |
|---|---|
| Parameter and return annotations (Python 3.12 and 3.13) | Immediately, when the `def` runs |
| Base classes of a generic class | Immediately, when the `class` runs |
| Upper bound `T: Bound` | Lazily, on first access to `__bound__` |
| Constraints `T: (A, B)` | Lazily, on first access to `__constraints__` |
| Default `T = X` (3.13) | Lazily, on first access to `__default__` |
| Value of `type Alias = ...` | Lazily, on first access to `__value__` |
Python 3.14 makes ordinary annotations lazy as well, under PEP 649. The rows for bounds, constraints, defaults, and alias values do not change.
The diagram shows the order of events for a bound that names a class defined later in the file.
Forward references without quotes
The practical gain is that you no longer quote names that are defined further down. Here the bound refers to Later before Later exists:
def process[T: Later](item: T) -> T:
return item
class Later:
pass
print(process.__type_params__[0].__bound__) # <class '__main__.Later'>With the older TypeVar, the same file needs a string, and the string stays unresolved at runtime:
from typing import TypeVar
T = TypeVar("T", bound="Later")
class Later:
pass
print(repr(T.__bound__)) # ForwardRef('Later')Under the new syntax, __bound__ holds the real class. Under the old syntax it holds a ForwardRef that you must resolve yourself.
Recursive and forward-declared aliases
The same laziness is what allows a type alias to mention itself or to mention classes that do not exist yet:
type Tree = Leaf | Branch
class Leaf:
value: int = 0
class Branch:
left: Tree
right: Tree
print(Tree.__value__) # __main__.Leaf | __main__.BranchThe right-hand side of type Tree = ... does not run when the statement executes. Python stores a small function for it. The first read of Tree.__value__ calls that function, and the result is cached for later reads.
An alias created with a plain assignment (Tree = Leaf | Branch) would fail on the first line with a NameError, because Leaf is not defined yet.
Errors appear late
Deferred evaluation moves the failure point. A misspelled bound does not fail when the module is imported:
def risky[T: Missing](x: T) -> T: # no error here
return x
try:
risky.__type_params__[0].__bound__
except NameError as error:
print(error) # name 'Missing' is not definedCalling risky(1) also works at runtime, because the bound is never consulted. Only a static checker, or code that reads __bound__, notices the typo. Run mypy or pyright over the file. Do not rely on importing the module as a test.
Evaluation order inside a single parameter list
The bound of one parameter cannot use another parameter from the same list as a name that is "not yet defined". The lazy scope already contains all of them, so Python resolves the names. Type checkers, however, reject a bound that depends on another type parameter, because bounds must be concrete types. Keep bounds free of other type parameters.
Defaults are different. A default may refer to an earlier parameter of the same list (Python 3.13):
class Pair[A, B = A]:
def __init__(self, first: A, second: B) -> None:
self.first = first
self.second = secondA bare Pair means Pair[Any, Any] to a checker. Pair[int] means Pair[int, int]. Parameters with defaults must come after parameters without them.
Introspection summary
These attributes let you inspect what the scope created:
| Attribute | Found on | Meaning |
|---|---|---|
| `__type_params__` | generic function, class, or alias | Tuple of the type parameter objects |
| `__bound__` | `TypeVar` | Evaluated upper bound, or `None` |
| `__constraints__` | `TypeVar` | Tuple of constraint types, empty if none |
| `__default__` | `TypeVar` | Evaluated default; check with `has_default()` first |
| `__value__` | alias made with `type` | Evaluated right-hand side |
Reading any of the lazy attributes triggers the evaluation. Each is computed once, then reused.
Common mistakes
- Using
Toutside its definition, for example in a module-level variable annotation, and expecting it to refer to the parameter. It raisesNameErrorwhen evaluated. Declare a new generic scope instead. - Calling
isinstance(value, Tree)on an alias made withtype. An alias is aTypeAliasTypeobject, not a class, so this raisesTypeError. UseTree.__value__or test against the concrete classes. - Assuming a lazy bound was checked at import. It was not. Only a type checker validates it.
- Naming a type parameter after a builtin or a module-level class and then wondering why a checker reports odd errors.
Exercise
In Python 3.12, what does this code print, and why does it not raise a NameError on the first line? type Shape = Circle | Square class Circle: ... class Square: ... print(Shape._value_)
Show answer
It prints __main__.Circle | __main__.Square. The right-hand side of a type statement is not evaluated when the statement runs. Python stores it and evaluates it on the first read of __value__. By then Circle and Square exist, so the lookup succeeds.
Exercise
A generic method is defined inside a class that has a nested class Config. The method is def load[C: Config](self, c: C) -> C. Why can the bound Config be written as a bare name, when a method body could not refer to Config without qualifying it?
Show answer
A type parameter's bound is evaluated inside an annotation scope. That scope can see names in the enclosing class body, unlike an ordinary function scope. The bound Config therefore resolves to the nested class. Code inside the method body follows the normal rule and would need Outer.Config.
Exercise
Which statement is true for def f[T: Missing](x: T) -> T: return x, where Missing is never defined? (a) Defining f raises NameError. (b) Calling f(1) raises NameError. (c) Defining and calling f both work, and the NameError appears only if f.__type_params__[0].__bound__ is read. Give the correct letter.
Show answer
(c). The bound is lazy and the function body never reads it. A static type checker would still report the undefined name.