Typing and Generics

typing.Generic

Declares a class parameterized by type variables. Explicit Generic bases support legacy declaration syntax; Python 3.12+ can declare parameters in the class header. Subscripted generics do not validate stored values at runtime.

Formal Syntax & Structure

python syntaxpython
class Name(typing.Generic[T]): ...

Return Value

generic base class

Typing construct or runtime result as described; static typing rules are not runtime validation.

Working Example

Example Snippetpython
from typing import Generic, TypeVar, get_origin
T=TypeVar('T')class Box(Generic[T]):    def __init__(self,value:T): self.value=valuebox=Box[int](7)print((box.value, get_origin(Box[int]) is Box))
Python Reference