Sub topic 13
Scoping and lazy evaluation of type parameters
This chapter assumes you can write generic functions and classes with the Python 3.12 syntax (def f[T], class C[T], type X = ...). It covers where a type parameter's name is visible and when Python evaluates the expressions attached to it.
Where a type parameter is visible
A type parameter declared in square brackets lives in its own scope. Python creates this scope between the surrounding scope and the definition itself. The name is visible in the signature, the body, and any scope nested inside them. It is not visible outside.
def first[T](items: list[T]) -> T:
def inner(x: T) -> T: # T is visible in nested functions
return x
return inner(items[0])
print(first([1, 2, 3])) # 1
print(T) # NameError: name 'T' is not definedThe legacy style differs here. T = TypeVar("T") creates an ordinary module-level variable, so any function in the module can use it. With the new syntax, each generic definition owns its parameters. Two functions that both declare [T] do not share a variable, so they cannot interfere with each other.
What is evaluated lazily
Python does not evaluate every expression in a type parameter list when it runs the def or class line. Three kinds of expression are deferred:
- the bound after the colon (
T: Item) - the constraint tuple (
T: (int, str)) - the default after
=(T = str)
The value of a type statement alias is deferred in the same way. Python evaluates these expressions only when something reads __bound__, __constraints__, __default__ or __value__.
Lazy evaluation means you can refer to a name that does not exist yet, without quoting it:
class Tree[T: Item]: # Item is defined below
def __init__(self, item: T) -> None:
self.item = item
class Item:
pass
param = Tree.__type_params__[0]
print(param.__bound__) # <class '__main__.Item'>With TypeVar, the bound is evaluated immediately, so the same code needs a string: TypeVar("T", bound="Item").
Recursive aliases work for the same reason. In type Json = dict[str, Json] | list[Json] | str | int | float | bool | None, the name Json is not looked up until you read Json.__value__. By then the alias exists.
type Nested = list[Nested] | int
print(Nested.__value__) # evaluated now, on first accessAnnotations are a separate question
Lazy evaluation of bounds and aliases does not make function annotations lazy. In Python 3.12 and 3.13, annotations such as items: list[Later] are still evaluated when the function is defined, unless you use quotes or from __future__ import annotations. Python 3.14 defers annotation evaluation by default. The rules in this chapter apply regardless of version.
Common mistakes
- Reusing a name from an enclosing generic. If
class Box[T]has a methoddef map[T](...), the innerTshadows the class'sT. Checkers flag this, and the code is almost always wrong. Give the method a different name, such asU. - Mixing styles. Do not use
Generic[T]as a base of a class that already has[T]in its header. Use one style per definition. - Reading
__bound__too early in a script. If the bound refers to a name that is still undefined, the access raisesNameError.
Exercise
In the following code, why does class Holder[T: Missing] not raise an error when it is defined, and when would an error appear?
class Holder[T: Missing]:
pass
class Missing:
pass
Show answer
The bound Missing is evaluated lazily, so defining Holder does not look the name up. An error would appear only if code read Holder.__type_params__[0].__bound__ before Missing was defined. Here Missing is defined right after, so the access succeeds.
Exercise
A module defines def a[T](x: T) -> T and def b(y: T) -> T and never assigns a variable called T. What happens with b, and how would the legacy TypeVar style differ?
Show answer
b uses T outside any type parameter scope, so the name is undefined. A type checker reports it, and Python 3.12 or 3.13 raises NameError when b is defined, because annotations are evaluated eagerly. With the legacy style, a module-level T = TypeVar("T") would be visible to both functions.