Skip to content
Tutorials Center
My learning

Topics

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.

Python
class Box:
    def __class_getitem__(cls, item):
        return f"{cls.__name__} of {item}"

print(Box[int])   # Box of <class 'int'>

Try it

Python Subscripting a class

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.

Python Generic classes with typing.Generic

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

Python
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 list and dict generic).
  • Instances are unaffected. Box[int]("x") creates an ordinary Box; the type argument is not stored on the instance and nothing checks it.
  • typing.Generic supplies it for you. Inherit from Generic[T], or use the Python 3.12 syntax class 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.abc and built-ins in hints. Prefer list[int] and collections.abc.Sequence[str] over the older typing.List[int].