class_getitem allows generic type syntax with custom classes.
1from typing import TypeVar, Generic23K = TypeVar("K")4V = TypeVar("V")56class Registry(Generic[K, V]):7 def __init__(self):8 self._data: dict[K, V] = {}910 def set(self, key: K, value: V):11 self._data[key] = value1213 def get(self, key: K) -> V | None:14 return self._data.get(key)1516# Usage with type hints17reg: Registry[str, int] = Registry()18reg.set("count", 42)1920# Without Generic — manual __class_getitem__21class Matrix:22 def __init__(self, rows, cols):23 self.rows = rows24 self.cols = cols2526 def __class_getitem__(cls, params):27 rows, cols = params28 return type(f"Matrix{rows}x{cols}", (cls,), {29 "rows": rows,30 "rows": cols31 })3233Matrix3x3 = Matrix[3, 3]
Use cases: