CKTIS / Python
typing.TypeVar
Relate parameter and result types through one variable inferred by a type checker.
Version: Python 3.14; repository image, production runtime not attested
Syntax
T = TypeVar("T", bound=str)Relate parameter and result types through one variable inferred by a type checker.
An upper bound accepts subtypes and can retain the particular subtype, while a constrained variable is solved as one of its listed constraint types. These restrictions do not enforce runtime argument checks.
The example preserves a string subclass by identity and still accepts an integer at runtime.
Examples
from typing import TypeVar
T = TypeVar("T", bound=str)
C = TypeVar("C", str, bytes)
def same(x: T) -> T:
return x
class Label(str): pass
tag = Label("x")
print(same(tag) is tag, same(4))
print(T.__bound__ is str, C.__constraints__ == (str, bytes))
Result
True 4 True True
The example preserves a string subclass by identity and still accepts an integer at runtime.