class_getitem enables generic type syntax with custom classes.
1from typing import TypeVar, Generic23K = TypeVar("K")4V = TypeVar("V")56class TypedDict(Generic[K, V]):7 def __init__(self):8 self._data: dict[K, V] = {}910 def __setitem__(self, key: K, value: V):11 self._data[key] = value1213 def __getitem__(self, key: K) -> V:14 return self._data[key]1516# Type-safe usage17users: TypedDict[str, int] = TypedDict()18users["alice"] = 25 # OK19# users["alice"] = "twenty-five" # Type error!2021# Custom class with __class_getitem__22class Matrix:23 def __init__(self, rows: int, cols: int):24 self.data = [[0] * cols for _ in range(rows)]2526 def __class_getitem__(cls, params):27 rows, cols = params28 class TypedMatrix(cls):29 pass30 TypedMatrix.rows = rows31 TypedMatrix.cols = cols32 return TypedMatrix3334Matrix3x3 = Matrix[3, 3]35m = Matrix3x3() # rows=3, cols=3
Benefits: