Python Glossary Русский

Python 3.12+Annotations & typingconstruct

Type parameters [T]

syntax

def f[T](x: T) -> T and class Box[T] declare generic functions and classes right in the header, without TypeVar or Generic (Python 3.12+).

Syntax

def имя[T](x: T) -> T: ...
class Имя[T]: ...
class Имя[T: Ограничение, *Ts, **P]: ...

The main trap: T is visible only inside its own function or class — outside it is a NameError, not a shared module variable as with T = TypeVar('T'). The type is not checked at runtime: first(['a']) runs however the function is annotated. Defaults [T = int] arrived only in 3.13; older versions still need TypeVar and Generic[T].

Examples

# Python 3.12+
def first[T](items: list[T]) -> T:
    return items[0]
print(first([3, 1]))  # → 3
print(first.__type_params__)  # → (T,)
print(T)  # → NameError
# Python 3.12+
class Box[T]:
    def __init__(self, item: T):
        self.item = item
print(Box[int])  # → __main__.Box[int]
print(Box('a').item)  # → a — тип не проверяется
# Python 3.13+
class Box[T = int]:
    pass
print(Box.__type_params__[0].__default__)  # → <class 'int'>

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy