Reusable typed response shapes
Several API results share a common shape but vary by payload type.
Python · Type Alias
A generic type alias is a reusable name for a type expression parameterized by one or more type variables. Modern Python declares its parameters in brackets after the alias name; static type checkers use them to form specialized aliases.
A generic type alias gives a reusable name to a type expression containing a type variable. Static type checkers substitute the supplied argument when the alias is specialized, while the alias does not change runtime behavior.
type Alias[T] = type_expression| Name | Type | Description |
|---|---|---|
T | type parameter | Type parameters determine the types substituted into the alias expression when it is specialized. |
A reusable generic type alias; it does not produce a runtime value conversion.
__type_params__.from collections.abc import Iterable
from typing import TypeVar
T = TypeVar("T")
Response = Iterable[T] | int
def handle(value: Response[str]) -> str:
if isinstance(value, int):
return str(value)
return ",".join(value)
print(handle(["ok", "done"]))
print(handle(200))The alias describes either an iterable of a chosen element type or an integer; the function specializes it for strings.
Several API results share a common shape but vary by payload type.
A library exposes collections or unions that should preserve an element type.
A codebase wants concise annotations for complex, repeated type expressions.
A generic type alias is a name for a type expression that includes one or more type variables. For example, Response = Iterable[S] | int can later be specialized as Response[str]. Type checkers use the specialization to substitute the type variable.
Follow-up: How can a modern Python declaration express a generic alias? Use type-parameter syntax, such as type Response[T] = Iterable[T] | int, when targeting a Python version that supports it.
Declare a TypeVar, place it in the aliased expression, and assign that expression to the alias. The documented compatibility pattern is S = TypeVar("S") followed by an alias such as Response = Iterable[S] | int.
Follow-up: What does the type variable mean? It represents a single type selected by the specialization, so Response[str] and Response[bytes] describe different iterable element types.
Generic type information primarily supports static type checkers. At runtime, generic objects behave much like their non-generic counterparts, so the alias is chiefly an annotation tool rather than runtime validation.
Follow-up: Can the alias enforce that a value is an iterable or integer at runtime? No; runtime checks must be implemented separately, for example with isinstance or explicit validation.
TypeVarTypeAliasTypeGenericIterabletype statement