ID EN
Typing

TypeVar

Python 3.11 🇮🇩 Bahasa Indonesia

Ketik variabel.

Syntax

PYTHON
class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False)

Contoh

Example 1
PYTHON
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
Example 2
PYTHON
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
Example 3
PYTHON
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
Example 4
PYTHON
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
Example 5
PYTHON
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

See Also

Generic TypeError