__class_getitem__Easy Examples

Called for subscripting a class (e.g. list[int]); used in generics

Implementing __class_getitem__

Basic implementation of __class_getitem__ in a class.

python
class Example:
    def __class_getitem__(self):
        return "Example __class_getitem__"

obj = Example()
print(obj)

__class_getitem__ called for subscripting a class (e.g. list[int]); used in generics. Implementing it lets you customize how Python interacts with your objects.

__class_getitem__ in action

Seeing __class_getitem__ called by Python's built-in operations.

python
# How Python calls __class_getitem__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __class_getitem__(self):
        print(f"__class_getitem__ was called!")
        return self

d = Demo(42)
# This triggers __class_getitem__:
print(d)

Python automatically calls __class_getitem__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground