Python Glossary Русский

Python 3.5+Annotations & typingterm

Generic[T]

generics

Base class for writing generic user-defined classes. The type parameters are declared with TypeVar.

Syntax

from typing import Generic, TypeVar
T = TypeVar('T')
class MyClass(Generic[T]): ...

Since Python 3.12 you no longer inherit from Generic or declare a TypeVar by hand — the type parameters go straight into the class header, in brackets after the name. Those parameters exist for the checker only: they are erased at runtime, so isinstance against a parameterized type raises TypeError. With several parameters, their order in Generic fixes the order callers must use when supplying concrete types.

Examples

from typing import Generic, TypeVar
T = TypeVar('T')
class Stack(Generic[T]):
    def __init__(self): self._items: list[T] = []
    def push(self, item: T) -> None: self._items.append(item)
    def pop(self) -> T: return self._items.pop()
s: Stack[int] = Stack()
s.push(1)
s.push(2)
print(s.pop())  # → 2
print(len(s._items))  # → 1
s.push(10)
print(s.pop())  # → 10
print(len(s._items))  # → 1

See also

Open in the full glossarydocs.python.orgReport an inaccuracy