Sub topic 11
Type parameter defaults (Python 3.13)
This chapter assumes you can write generic functions and classes with the [T] syntax, and that you know what bounds and constraints do. It also assumes you run a static checker such as mypy or pyright. Type parameter defaults are a Python 3.13 feature, and your checker must support them (specified in PEP 696).
What a default does
A type parameter without a default has to be supplied or inferred. If you write a bare Box in an annotation, the checker treats it as Box[Any]. This silently turns off checking for that value.
A default replaces that fallback with a type you choose. Write it after = in the parameter list:
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = body
def make() -> Response:
return Response("ok")In the annotation -> Response, the checker reads Response[str], not Response[Any]. The default is also what the checker uses when it cannot infer anything better.
Defaults are most useful when one type argument covers the common case and a few users need to override it. A library author can add a new type parameter without breaking existing code. Code that wrote bare Response keeps its meaning, as long as the new parameter has a default.
Inference beats the default
A default is a fallback, not an override. When the checker can infer the type argument from the call, it uses the inferred type:
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = body
a = Response("ok") # inferred Response[str]
b = Response(404) # inferred Response[int], the default is ignored
c: Response = Response(404) # error: Response means Response[str]Line c fails because the annotation Response stands for Response[str], and a Response[int] is not assignable to it (the class is invariant in T, since body is a mutable attribute). Before defaults, the bare Response meant Response[Any], and this line passed. Adding a default to an existing class can therefore expose errors in code that used the bare name.
Partial specialization
When a class has several parameters, defaults let callers supply only the leading ones. Here is a result type whose error type is usually Exception:
from dataclasses import dataclass
@dataclass
class Result[T, E = Exception]:
value: T | None = None
error: E | None = None
def parse(text: str) -> Result[int]:
try:
return Result(value=int(text))
except ValueError as exc:
return Result(error=exc)
print(parse("12"))
print(parse("x"))Result[int] means Result[int, Exception]. A caller who wants a narrower error type writes Result[int, ValueError].
At runtime the subscription Result[int] also works on Python 3.13. The interpreter fills in the missing argument from the default. Without a default, Result[int] would raise a TypeError for too few arguments.
Ordering rules
Defaults follow the same rule as function parameters. Once one type parameter has a default, every later one needs a default too:
class Ok[A, B = int, C = str]:
passWriting class Bad[T = int, U] is a SyntaxError on Python 3.13, with a message saying a non-default type parameter follows a default one. The compiler rejects it before your program runs. For legacy TypeVar objects, the check happens when the class is created, and it raises a TypeError.
A default can refer to an earlier parameter in the same list:
class Mapping2[K, V = K]:
def __init__(self, data: dict[K, V]) -> None:
self.data = data
def identity_map() -> Mapping2[str]:
return Mapping2({"a": "a"})Mapping2[str] means Mapping2[str, str]. A default may only refer to parameters declared before it, never after. It also cannot refer to a parameter of a different kind in a way that changes its meaning. For example, a TypeVar default cannot be a ParamSpec.
Defaults with bounds and constraints
A default must satisfy the parameter's bound or constraints. The checker verifies this when it reads the definition:
from collections.abc import Sized
class Holder[T: Sized = list[int]]:
def __init__(self, item: T) -> None:
self.item = item
class Echo[T: (int, str) = int]:
def __init__(self, item: T) -> None:
self.item = itemFor Holder, list[int] is Sized, so the default is accepted. A default of int would be rejected because int has no __len__. For Echo, the default has to be one of the listed constraints. Writing = float there is an error.
ParamSpec and TypeVarTuple defaults
All three kinds of type parameter accept defaults, with different default shapes.
| Kind | Declaration | Default value must be |
|---|---|---|
| `TypeVar` | `[T = str]` | a single type |
| `ParamSpec` | `[**P = [int, str]]` | a parameter list in brackets, `...`, or another `ParamSpec` |
| `TypeVarTuple` | `[*Ts = *tuple[int, int]]` | an unpacked tuple type |
Here is a ParamSpec default for a task wrapper whose arguments are usually an int and a str:
from collections.abc import Callable
class Task[**P = [int, str], R = None]:
def __init__(self, func: Callable[P, R]) -> None:
self.func = func
def run(self, *args: P.args, **kwargs: P.kwargs) -> R:
return self.func(*args, **kwargs)
def annotate(t: Task) -> None:
passThe bare Task in annotate means Task[[int, str], None].
A TypeVarTuple default uses an unpacked tuple, since the parameter stands for a sequence of types:
class Shape[*Ts = *tuple[int, int]]:
def __init__(self, *dims: *Ts) -> None:
self.dims = dims
def area(s: Shape) -> None:
passHere Shape alone means a shape with two int dimensions. The checker will complain if you pass Shape a value created with three arguments, because it is inferred as Shape[int, int, int].
How the checker picks a type argument
For each type parameter, the checker follows this order of preference.
The last two branches matter most for annotations. An annotation such as x: Response has no call to infer from, so it falls through to the default. Without a default it falls through to Any.
Legacy TypeVar with a default
The same feature exists for the pre-3.12 style. In Python 3.13 and later, typing.TypeVar takes a default= argument. For older versions, import TypeVar from typing_extensions, which backports it:
from typing import Generic
from typing_extensions import TypeVar
T = TypeVar("T", default=str)
class Response(Generic[T]):
def __init__(self, body: T) -> None:
self.body = bodyHere Response behaves exactly like the class Response[T = str] version. If you must support Python 3.11 or earlier, this is the only form that works. The [T = str] syntax is a syntax error on any interpreter older than 3.13.
What exists at runtime
The default is stored on the type parameter object. It is metadata that tools can read, but Python itself never applies it to your values:
import typing
class Response[T = str]:
def __init__(self, body: T) -> None:
self.body = body
class Plain[T]:
pass
t = Response.__type_params__[0]
print(t.has_default()) # True
print(t.__default__) # <class 'str'>
p = Plain.__type_params__[0]
print(p.has_default()) # False
print(p.__default__ is typing.NoDefault) # TrueThe default is evaluated lazily, like bounds and constraints in the new syntax. The expression after = runs only when you first read __default__. This means a default can refer to a name defined later in the module, and the reference is checked when somebody asks for it, not when the class statement runs.
Checking isinstance(x, Response) ignores the default, because Response[str] and Response[int] are the same class at runtime. As the earlier chapter on runtime erasure showed, the checker is the only tool that enforces type arguments.
Common errors
- A new default breaks old code. Code that used the bare class name was
Anybefore and is now strictly typed. Review such annotations when you add a default to a published class. - Expecting the default to win over inference.
Response(404)isResponse[int]. The default applies only when nothing else determines the type. - Placing a default before a non-default. This is a
SyntaxErrorwith the new syntax. - A default outside the bound. The checker reports it at the definition, not at the use site.
- Using the
[T = X]syntax on Python 3.12. The interpreter fails to compile the file. Usetyping_extensions.TypeVarthere. - Checker support lag. Older checker versions may ignore or reject defaults, so confirm your version before depending on them.
Exercise
A class is declared as class Cache[K, V = K, T = int]. What do the annotations Cache[str] and Cache[str, bytes] mean? Would class Cache[K = str, V] be allowed?
Show answer
Cache[str] means Cache[str, str, int], because V defaults to K and T defaults to int. Cache[str, bytes] means Cache[str, bytes, int]. class Cache[K = str, V] is not allowed: V has no default but follows K, which does, so Python raises a SyntaxError.
Exercise
Given class Response[T = str] with __init__(self, body: T), what type does a checker give Response(404), and what does the annotation x: Response mean?
Show answer
Response(404) is inferred as Response[int], because inference is preferred over the default. The annotation x: Response means Response[str], because an annotation offers nothing to infer from, so the default is used.