CKTIS / Python
typing.Generic
Declare a generic class using Generic[T] as its base and a previously declared type variable T as the argument.
Version: Python 3.14; repository image, production runtime not attested
Syntax
class Box(Generic[T]): ...Declare a generic class using Generic[T] as its base and a previously declared type variable T as the argument.
In Python 3.14 class Box[T] is the corresponding modern declaration. The specialization records type arguments, but constructing a Box[int] does not check the type of its value.
The example reads the origin and argument from the specialization before storing a string.
Examples
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)
Result
True True True note
The example reads the origin and argument from the specialization before storing a string.