CKTIS / Python
typing.Generic
A base Generic[T] declara uma classe com uma variável de tipo T criada anteriormente.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
class Box(Generic[T]): ...A base Generic[T] declara uma classe com uma variável de tipo T criada anteriormente.
A sintaxe moderna class Box[T] também introduz um parâmetro de tipo.
A especialização Box[int] conserva o argumento para inspeção mas não valida o valor e aceita a cadeia.
Exemplos
from typing import Generic, TypeVar, get_args, get_origin
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
spec = Box[int]
print(get_origin(spec) is Box, get_args(spec) == (int,))
box = spec("note")
print(type(box) is Box, box.value)
Resultado
True True True note
A especialização Box[int] conserva o argumento para inspeção mas não valida o valor e aceita a cadeia.