Python __class_getitem__ Method
Last modified November 17, 2026 Python 3.15
Square brackets usually mean indexing, but they also appear in type hints such
as list[int] or dict[str, int]. For a class object,
C[key] is handled by __class_getitem__, a hook added in
Python 3.7 by PEP 560. This article shows how the hook is called, what it
receives, how the built-in generic types use it, and how to build your own
subscriptable classes without breaking type checkers.
How subscription works
The expression obj[key] is executed as
type(obj).__getitem__(obj, key). A class is itself an object, so
C[key] would normally look for __getitem__ on the
metaclass. To make generic type hints possible, the interpreter special-cases
classes: when __class_getitem__ exists on the class, it is called
instead, and it is automatically treated as a class method.
class Box:
def __class_getitem__(cls, item):
print("parameter received:", item)
return item
print(Box[int])
print(Box[int, str])
print(Box[1 + 2])
print(Box.__class_getitem__)
The hook receives the class as cls and the expression inside the
brackets as item. One parameter arrives as a single object, while
several parameters separated by commas arrive as one tuple. The hook may return
anything; here it returns the argument unchanged, which is why
Box[int] prints the class int. Accessing
Box.__class_getitem__ shows that Python bound it as a method of the
class.
$ python basic.py parameter received: <class 'int'> <class 'int'> parameter received: (<class 'int'>, <class 'str'>) (<class 'int'>, <class 'str'>) parameter received: 3 3 <bound method Box.__class_getitem__ of <class '__main__.Box'>>
Validating type parameters
Because the hook is ordinary Python code, it can reject invalid parameters with
a clear message. The next example defines Pair, which requires
exactly two types and returns a small alias object that records them. Checking
isinstance(params, tuple) matters: a single parameter is never a
tuple, and a tuple parameter may have any length.
class PairAlias:
def __init__(self, left, right):
self.left = left
self.right = right
def __repr__(self):
return f"Pair[{self.left.__name__}, {self.right.__name__}]"
class Pair:
def __class_getitem__(cls, params):
if not isinstance(params, tuple) or len(params) != 2:
raise TypeError("Pair expects exactly two type parameters")
left, right = params
if not isinstance(left, type) or not isinstance(right, type):
raise TypeError("Pair parameters must be types")
return PairAlias(left, right)
print(Pair[int, str])
print(Pair[int, str].left)
print(Pair[int, str].right)
for expr in (lambda: Pair[int], lambda: Pair[int, str, float],
lambda: Pair[1, str]):
try:
print(expr())
except TypeError as e:
print(type(e).__name__, e)
The valid subscription returns a PairAlias whose representation is
readable and whose attributes expose the two types. The invalid forms fail
before an alias is built: one argument and three arguments break the length
check, and the integer 1 is not a type. Validating here keeps
mistakes close to the line that made them.
$ python pair.py Pair[int, str] <class 'int'> <class 'str'> TypeError Pair expects exactly two type parameters TypeError Pair expects exactly two type parameters TypeError Pair parameters must be types
Generic classes and typing
The standard way to declare a generic class is to inherit from
typing.Generic. Its own __class_getitem__ builds a
typing alias, and the alias records the origin and the arguments.
When the alias is called, the instance receives an __orig_class__
attribute, which a library can inspect at runtime.
from typing import Generic, TypeVar, get_args, get_origin
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, item):
self.item = item
box = Box[int](5)
print(Box[int])
print(get_origin(Box[int]))
print(get_args(Box[int]))
print(box.item)
print(box.__orig_class__)
Box[int] is an alias, not a new class. get_origin()
returns the original Box, and get_args() returns
(int,), which is how generic code discovers the parameter. Calling
the alias creates a normal Box instance and sets
__orig_class__ on it. Type checkers read the alias statically;
Python itself does not enforce that the item is an int.
$ python box_typing.py __main__.Box[int] <class '__main__.Box'> (<class 'int'>,) 5 __main__.Box[int]
Reusing types.GenericAlias
A class that does not need custom logic can borrow the implementation used by
the built-in containers. Assigning types.GenericAlias as a
classmethod gives the class the same alias object as list[int],
including the printable form and the get_origin() and
get_args() support.
import types
from typing import get_args, get_origin
class Vector:
def __init__(self, values):
self.values = list(values)
Vector.__class_getitem__ = classmethod(types.GenericAlias)
alias = Vector[int]
print(alias)
print(type(alias).__name__)
print(get_origin(alias))
print(get_args(alias))
The alias prints as __main__.Vector[int] and is an instance of
types.GenericAlias. This is the mechanism behind PEP 585, which
made list[int] and similar hints available without importing
typing. The assignment can also be written inside the class body
with a decorator-free method, but the explicit form shows that the hook is just
an attribute.
$ python generic_alias.py __main__.Vector[int] GenericAlias <class '__main__.Vector'> (<class 'int'>,)
Runtime specialization
Subscription does not have to produce a type hint. A common pattern is a
factory that returns a subclass bound to a model, a schema, or a configuration.
The next example builds a Query class that specializes itself for a
Model subclass and validates the argument at subscription time.
class Model:
table = None
class User(Model):
table = "users"
class Post(Model):
table = "posts"
class Query:
def __class_getitem__(cls, model):
if not (isinstance(model, type) and issubclass(model, Model)):
raise TypeError("Query[...] expects a Model subclass")
name = f"{cls.__name__}[{model.__name__}]"
return type(name, (cls,), {"model": model})
UserQuery = Query[User]
PostQuery = Query[Post]
print(UserQuery.__name__)
print(UserQuery.model.table)
print(PostQuery.model.table)
print(issubclass(UserQuery, Query))
print(Query[User] is Query[User])
try:
Query[42]
except TypeError as e:
print(type(e).__name__, e)
Each subscription creates a new class with a readable name and a
model attribute. Two subscriptions with the same argument produce
two different classes, which is fine for a factory but surprising if callers
compare aliases with is. A cache dictionary keyed by the model
fixes that when identity matters.
$ python query.py Query[User] users posts True False TypeError Query[...] expects a Model subclass
Metaclass precedence
The special case applies only when the metaclass does not define
__getitem__. If it does, normal subscription wins and
__class_getitem__ is never called. This matters for framework
classes whose metaclass implements a registry lookup or a declarative syntax.
class Meta(type):
def __getitem__(cls, item):
return f"metaclass lookup: {item}"
class WithMetaclass(metaclass=Meta):
def __class_getitem__(cls, item):
return f"class_getitem: {item}"
class WithoutMetaclass:
def __class_getitem__(cls, item):
return f"class_getitem: {item}"
print(WithMetaclass[int])
print(WithoutMetaclass[int])
print(type(WithMetaclass.__class_getitem__))
Both classes define the hook, but only the one with a plain metaclass uses it.
For WithMetaclass, the interpreter calls
Meta.__getitem__ because the metaclass provides it. The last line
confirms that the hook itself is still an ordinary method; it is simply not
reached by the subscription syntax.
$ python metaclass.py metaclass lookup: <class 'int'> class_getitem: <class 'int'> <class 'method'>
Classes and instances are different
__class_getitem__ applies to the class object only. An instance of
the class is subscripted through __getitem__, and if that method is
missing the instance is not subscriptable. Mixing the two hooks is a common
source of confusion when a class supports both generic hints and container
access.
class Row:
def __class_getitem__(cls, key):
return f"column {key}"
print(Row["name"])
row = Row()
try:
print(row["name"])
except TypeError as e:
print(type(e).__name__, e)
The class subscription returns the column description, but the instance has no
__getitem__, so row["name"] fails with
TypeError. A class that should support both needs two separate
methods, and the instance method should implement real container semantics
rather than return a hint.
$ python instances.py column name TypeError 'Row' object is not subscriptable
Best practices
Use the hook for type-level metadata, not as a replacement for normal indexing:
- Keep
__class_getitem__side-effect free when it serves type hints; a cache should not change the meaning of a subscription. - Accept both a single object and a tuple, and validate the number and kind of parameters explicitly.
- Return an object that is useful for introspection, such as a
types.GenericAliasor an alias with__origin__and__args__. - Do not rely on
isidentity for newly created aliases unless you cache them. - Remember that a metaclass
__getitem__takes precedence over__class_getitem__. - For ordinary generics, inherit from
typing.Genericinstead of reimplementing the alias machinery.
Source
object.__class_getitem__ - Python documentation
types.GenericAlias - Python documentation
PEP 560 - Core support for typing module and generic types
In this article we have implemented the __class_getitem__ method.
We have covered class subscription, parameter validation, typing
generics, types.GenericAlias, runtime specialization, metaclass
precedence, and the difference between class and instance subscription.
For related topics, see Python __getitem__ method,
Python metaclasses,
Python type built-in, and
Python data types.
Author
List all Python tutorials.