Sub topic 11
Type parameter defaults (Python 3.13)
This chapter assumes you can write generic classes and functions with the Python 3.12 syntax (class C[T], def f[T]) and that you run a static type checker such as mypy or pyright. Type parameter defaults come from PEP 696 and are available in the language from Python 3.13.
The problem defaults solve
Suppose a library defines a generic Response[T] class. Most responses carry a string body, but a few carry bytes or parsed JSON. Without defaults, every use of the bare name Response leaves T unspecified. A checker then treats it as Response[Any], and you lose type safety exactly where you wanted it.
A default gives T a fallback type. When a user writes Response with no type argument, the checker substitutes the default.
Declaring a default
Write the default after = inside the brackets:
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = body
def make() -> Response:
return Response("ok")In make, the annotation Response means Response[str]. A caller who needs another type still writes it explicitly, as in Response[bytes].
Defaults versus inference
A default applies only when the checker has nothing else to go on. When a call supplies a value, inference wins:
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = body
a = Response("text") # inferred Response[str]
b = Response(b"raw") # inferred Response[bytes], not the default
c: Response = Response("x") # bare annotation means Response[str]The default matters most in annotations, in base-class lists, and in constructors that do not mention T in their parameters.
Ordering rules
A type parameter with a default cannot be followed by one without a default. This mirrors how function parameters work.
class Pair[K, V = int]: # valid
pass
# class Bad[K = str, V]: ... # error: non-default after defaultA default can also refer to an earlier type parameter:
class Mapping2[K, V = K]:
def __init__(self, key: K, value: V) -> None:
self.key = key
self.value = valueHere a bare Mapping2[int] means Mapping2[int, int].
Defaults must respect bounds
A default has to satisfy the parameter's bound or constraints. A default of int is fine for T: float, since int is accepted where float is expected. A default of str for T: Sized is also fine, because str supports len(). A default that violates the bound is a checker error.
from collections.abc import Sized
class Container[T: Sized = list[int]]:
def __init__(self, data: T) -> None:
self.data = dataDefaults for ParamSpec and TypeVarTuple
The same feature extends to the other kinds of type parameters. A ParamSpec default is a list of parameter types, and a TypeVarTuple default is an unpacked tuple:
class Handler[**P = [int, str]]:
pass
class Shape[*Ts = *tuple[int, int]]:
passThese are less common. Most code only needs defaults on plain type parameters.
Common errors
- Expecting a runtime effect. The default is for the checker. At runtime,
Response("ok")is an ordinary object and nothing enforcesstr. - Putting a default before a non-default parameter. Reorder the parameters or give every later one a default.
- Using a default that breaks the bound. The checker reports it at the class definition.
- Targeting older Python. On 3.12 the
= strsyntax is a syntax error. For older versions,typing_extensionsprovidesTypeVar("T", default=str).
Exercise
Given class Box[T = int]: ... and the annotation x: Box, what type does a checker assign to x? What changes if the code is y = Box("hi") with a constructor __init__(self, value: T)?
Show answer
The annotation x: Box means Box[int], because nothing else determines T and the default applies. For y = Box("hi"), the checker infers Box[str] from the argument, so the default is not used.
Exercise
Why is class Bad[K = str, V]: ... rejected, and how do you fix it?
Show answer
A type parameter without a default cannot follow one that has a default. Fix it by reordering to class Good[V, K = str] or by giving V a default too, as in class Good[K = str, V = int].