Python Reference ยท Classes and Special Methods
__class_getitem__() and generics
Reference for Python __class_getitem__(): how list[int] style subscripting works, how to make your own class generic, and how it relates to typing.Generic.
__class_getitem__() lets you write MyClass[int]: subscripting the class itself rather than an instance. Built-in containers use it, which is why list[int], dict[str, int] and tuple[int, ...] work as type hints since Python 3.9.
It is a class method that receives whatever is inside the brackets. The usual implementation returns types.GenericAlias(cls, params), an object that remembers the class and its type arguments. The subscript has no effect at run time; it only documents intent for type checkers.
class Box: def __class_getitem__(cls, item): return f"{cls.__name__} of {item}" print(Box[int]) # Box of <class 'int'>
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class Container: def __class_getitem__(cls, item): ...
| Name | Description |
|---|---|
cls |
The class being subscripted. Python makes the method an implicit class method. |
item |
The expression in the brackets: a single object, or a tuple when you write Cls[a, b]. |
Return value: anything; by convention a types.GenericAlias. The result of Cls[int] is that returned object, not an instance.
Raises: only what your implementation raises. Without the method, subscripting a class gives TypeError: type 'X' is not subscriptable.
Usage notes
- Added in Python 3.9 (PEP 560 provided the hook; 3.9 made built-ins such as
listanddictgeneric). - Instances are unaffected.
Box[int]("x")creates an ordinaryBox; the type argument is not stored on the instance and nothing checks it. typing.Genericsupplies it for you. Inherit fromGeneric[T], or use the Python 3.12 syntaxclass Pair[A, B]:, and the method is generated. Write your own only for a lightweight alias.- Multiple parameters arrive as a tuple, so
Cls[int, str]passes(int, str). - Precedence. A metaclass
__getitem__is tried before__class_getitem__; it is a rarely used alternative. - Not for instance subscripting.
obj[key]still uses__getitem__. - Use
collections.abcand built-ins in hints. Preferlist[int]andcollections.abc.Sequence[str]over the oldertyping.List[int].