Subscriptable Classes Without a Metaclass: Python's __class_getitem__

This article explains how Python's __class_getitem__ makes a class subscriptable, why it should return a GenericAlias, how a metaclass takes precedence over it, how it relates to the generic syntax of Python 3.12, and what it does not check at run time.

A green tree python with white and yellow markings coiled around a bare branch, its head resting on its coils against a blurred green background.
Photo by Antonio Janeski on Unsplash

Annotations such as list[str] or dict[int, str] subscript a class, not an instance, and for a long time only the built-in containers and the classes of typing accepted that syntax. The present article addresses the special method __class_getitem__, introduced by PEP 560 in Python 3.7, which Python calls when a class is subscripted, so that a user-defined class can accept Box[int] without a metaclass. The method, the object it should return, the rule that decides between it and a metaclass, and its relation to the generic syntax of Python 3.12 are examined in turn, together with the limits of what it checks at run time. Letting a class describe its own parameterized forms, so that the annotations of a library read like those of the standard library, is the secret weapon of __class_getitem__.

Subscribing a Class

When the expression obj[x] is evaluated, Python first looks for __getitem__ on the type of obj; only if that is absent and obj is a class does it call obj.__class_getitem__(x). The method is a class method automatically, without the decorator, and the data model documentation states that it should return a types.GenericAlias, an object that records the original class and the arguments. The following example compares a class without the method, a class that returns a GenericAlias and a class that returns itself, as many introductory examples do.

import typing
from types import GenericAlias


class Plain:
    pass


class Box:
    def __init__(self, content):
        self.content = content

    __class_getitem__ = classmethod(GenericAlias)


class SelfReturning:
    def __class_getitem__(cls, item):
        return cls


try:
    Plain[int]
except TypeError as error:
    print(error)  # Output: type 'Plain' is not subscriptable

alias = Box[int]
print(alias)                                # Output: __main__.Box[int]
print(alias.__origin__, alias.__args__)     # Output: <class '__main__.Box'> (<class 'int'>,)
print(typing.get_args(Box[int, str]))       # Output: (<class 'int'>, <class 'str'>)
print(type(alias(5)).__name__, alias(5).content)  # Output: Box 5
print(SelfReturning[int] is SelfReturning)  # Output: True

The alias remembers both the class and its arguments, which is what typing.get_origin, typing.get_args and documentation tools read, and calling it creates an ordinary instance of Box. The version that returns cls runs without error but discards the argument, so SelfReturning[int] is indistinguishable from SelfReturning and no tool can recover the parameter. The relation of this method to __getitem__ and the other special methods is part of the protocol described in the article devoted to the data model.

Item Tooltips: What the Subscription Records

An item tooltip in a game describes what an object is, its type and its properties, without changing what the object can do. Likewise, Box[int] describes the intended content of a box for readers and tools, while the box itself accepts anything. The analogy, however, stops at this point, because a tooltip is generated from the item itself, whereas the parameters of an alias come only from the annotation and are never compared with the stored values. Static type checkers do not even execute the method: they read the class definition, and they treat a class as generic only when it derives from typing.Generic or uses the type-parameter syntax of Python 3.12, both of which supply __class_getitem__ themselves, as described in the article devoted to advanced type hints. A metaclass that defines __getitem__, moreover, takes precedence over the method, which is how Enum turns subscription into a lookup of members. The following example shows the precedence rule and the generic syntax that should normally be preferred.

import enum
import typing


class Meta(type):
    def __getitem__(cls, key):
        return f"metaclass lookup of {key.__name__}"


class Widget(metaclass=Meta):
    def __class_getitem__(cls, item):
        return "never reached"


print(Widget[int])  # Output: metaclass lookup of int


class Color(enum.Enum):
    RED = 1


print(Color["RED"])  # Output: Color.RED


class Stack[T]:
    def __init__(self):
        self.items: list[T] = []

    def push(self, item: T) -> None:
        self.items.append(item)


print(Stack.__type_params__)            # Output: (T,)
print(Stack[int], typing.get_origin(Stack[int]) is Stack)  # Output: __main__.Stack[int] True

The syntax class Stack[T] declares the type parameter, makes the class generic for type checkers and provides a __class_getitem__ that validates the number of arguments. Writing the method by hand is therefore justified only when a class must support subscription without becoming a typing generic, for example in a library that has to run on versions earlier than 3.12 and wants to avoid typing.Generic, or when the class needs the lighter GenericAlias. The documentation discourages other uses, such as building classes dynamically or validating values through subscription.

Pitfalls of class_getitem

The method records parameters but enforces none of them, so its pitfalls come from expecting a runtime effect that does not exist. Six pitfalls are distinguished, which are the following:

  1. No runtime checking. Box[int]("text") creates a box that contains a string, because the arguments are not used when an instance is created.
  2. No arity checking. A hand-written classmethod(GenericAlias) accepts Box[int, str, bytes] as readily as Box[int].
  3. isinstance refuses aliases. isinstance(x, Box[int]) raises TypeError, so checks must use the plain class.
  4. Returning cls. A method that returns the class itself discards the parameters.
  5. Metaclass precedence. A metaclass with __getitem__ silently replaces the method, so subscription may perform a lookup instead of creating an alias.
  6. Equality, not identity. Two evaluations of Box[int] produce equal but distinct objects, so comparisons must use ==.

The first three pitfalls and the last one are reproduced in the following example, together with a measurement of the cost of subscription.

import timeit
from types import GenericAlias


class Box:
    def __init__(self, content):
        self.content = content

    __class_getitem__ = classmethod(GenericAlias)


class Stack[T]:
    pass


print(Box[int]("text").content)          # Output: text
print(Box[int, str, bytes].__args__)     # Output: (<class 'int'>, <class 'str'>, <class 'bytes'>)
try:
    isinstance(Box(1), Box[int])
except TypeError as error:
    print(error)  # Output: isinstance() argument 2 cannot be a parameterized generic
print(Box[int] == Box[int], Box[int] is Box[int])  # Output: True False

t_alias = min(timeit.repeat(lambda: Box[int], number=200_000, repeat=5))
t_generic = min(timeit.repeat(lambda: Stack[int], number=200_000, repeat=5))
print(t_generic > 2 * t_alias)  # Output: True

On CPython 3.12, subscribing the class with a plain GenericAlias took about 86 nanoseconds, against about 430 for a class declared with the type-parameter syntax, whose alias also checks the arguments. Both figures matter only when subscription runs inside loops, because annotations are normally evaluated once, and since Python 3.14 annotations of functions and classes are evaluated lazily.

Choosing How to Make a Class Subscriptable

Consequently, the generic syntax covers almost every need, and a hand-written __class_getitem__ remains a tool for narrow cases, as the following table summarizes.

Situation Recommended approach
A generic container checked by type checkers class Box[T]: (Python 3.12 and later)
The same on earlier versions Subclassing typing.Generic[T]
Subscription for annotations without typing machinery __class_getitem__ = classmethod(GenericAlias)
Subscription that looks something up, as in enumerations A metaclass with __getitem__
Validation of contents at run time Explicit checks in __init__ or a validation library
Dynamic creation of classes A factory function, not subscription

Conclusion

It is concluded that __class_getitem__ is the hook that Python calls when a class is subscripted, that it should return a GenericAlias recording the class and its arguments, and that a metaclass __getitem__ takes precedence over it. This magic is descriptive rather than protective: it informs readers and tools, but it checks neither the number of parameters nor the values stored, and type checkers rely on Generic or the type-parameter syntax instead. The runtime use of annotations, from typing.get_type_hints to the lazy evaluation introduced in Python 3.14, remains a natural subject for future articles of this series.