32.7 __class_getitem__ and Generic Classes
In Python, the __class_getitem__ special method is a cornerstone for creating generic classes—classes that are parameterized by one or more types. Introduced in Python 3.7 via PEP 560, it provides a mechanism for classes to support square-bracket notation ([]) for type hinting purposes without immediately creating a new class or metaclass. This method is fundamentally different from __getitem__ which operates on instances; __class_getitem__ is called on the class itself. The Purpose of class_getitem The primary purpose of __class_getitem__ is to enable type parameterization for static type checkers. When you write list[int], you are not, in fact, creating a new type of list at runtime. For the Python interpreter, this operation is largely ornamental. Its real consumer is a static type checker like mypy or Pyright. These tools understand that list[int] signifies a list where all elements are of type int. The __class_getitem__ method allows a class to define what should be returned when this subscripting syntax is used on it, enabling the rich ecosystem of generic type hints we have today.