Python Glossary Русский

Python 3.5+Annotations & typingterm

typing.TypeVar

generics

A type variable used to write generic functions and classes. Constraints are given with bound= or as an explicit list of types.

Syntax

from typing import TypeVar
T = TypeVar('T')
T = TypeVar('T', bound=SomeType)
T = TypeVar('T', int, str)

A TypeVar only earns its keep when the same variable appears at least twice in a signature — that is how you tie the return type to the argument type. A T used in just one place buys you nothing and is effectively Any. Note the two kinds of restriction: bound=X accepts X and any subclass, while the value form TypeVar('T', int, str) allows exactly int or exactly str and nothing in between. Python 3.12 offers a shorter spelling, def first[T](lst: list[T]) -> T, with no separate variable to declare.

Examples

# Python 3.9+
from typing import TypeVar
T = TypeVar('T')
def first(lst: list[T]) -> T:
    return lst[0]
print(first([1, 2, 3]))  # → 1
print(first(['a', 'b']))  # → 'a'
from typing import TypeVar
N = TypeVar('N', int, float)
def double(x: N) -> N:
    return x * 2
print(double(3))  # → 6
print(double(1.5))  # → 3.0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy