Type variable.
class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)
T = TypeVar('T') Can be anything
S = TypeVar('S', bound=str) Can be any subtype of str
A = TypeVar('A', str, bytes) Must be exactly str or bytes
def repeat(x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def print_capitalized(x: S) -> S:
"""Print x capitalized, and return x."""
print(x.capitalize())
return x
def concatenate(x: A, y: A) -> A:
"""Add two strings or bytes objects together."""
return x + y
x = print_capitalized('a string')
reveal_type(x) revealed type is str
class StringSubclass(str):
pass
y = print_capitalized(StringSubclass('another string'))
reveal_type(y) revealed type is StringSubclass
z = print_capitalized(45) error: int is not a subtype of str
U = TypeVar('U', bound=str|bytes) Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs) Can be anything with an __abs__ method
a = concatenate('one', 'two')
reveal_type(a) revealed type is str
b = concatenate(StringSubclass('one'), StringSubclass('two'))
reveal_type(b) revealed type is str, despite StringSubclass being passed in
c = concatenate('one', b'two') error: type variable 'A' can be either str or bytes in a function call, but not both