Python glossary entry

Generic

typing.Generic
Namespace
Standard library
Module
typing
Available since
Python 3.5

Declares a class parameterized by one or more type variables on pre-3.12-compatible syntax.

Definition

Generic makes type parameters explicit on class syntax compatible with Python versions before 3.12. A checker can then distinguish Box[int] from Box[str] while both remain ordinary Box instances at runtime.

A type-preserving container

Pyodide / WebAssembly
from typing import Generic, TypeVar

T = TypeVar("T")

class Box(Generic[T]):
    def __init__(self, value: T) -> None:
        self.value = value

    def get(self) -> T:
        return self.value

number = Box[int](42)
label = Box[str]("deepcut")

print("[result] integer box value:", number.get())
print("[result] string box value:", label.get())
print("[check] both values use the same runtime class:", type(number) is type(label))

The parameter belongs primarily to static analysis. Runtime instances do not become separate generated classes for every argument.

Use it when

Use a generic class when methods preserve or transform a type relationship across stored state. A container returning only object loses information its caller already supplied.

For Python 3.12 and newer, class Box[T]: expresses the same intent directly. Use Generic when the project supports older interpreters or when consistency with existing declarations matters.

Common mistake

Do not add a type parameter that never affects a public attribute, argument, or return value. An unused parameter gives readers another name to track without expressing a relationship.

Primary sourceOfficial Python documentation ↗