Python › Metaclasses & Class Customization

How does __class_getitem__ enable generic-looking syntax like MyClass[int]?

Advanced

Answer

__class_getitem__(cls, item) is called when you subscript a class itself (not an instance), like `list[int]` or a custom `Container[str]`. It's primarily used to support type-hint syntax for generic classes without requiring inheritance from typing.Generic, returning a types.GenericAlias or custom object representing the parameterized type.
class Container:
    def __class_getitem__(cls, item):
        return f'{cls.__name__}[{item.__name__}]'

print(Container[int])  # 'Container[int]'
print(list[int])       # list[int] -- built-in generics support this too
Real-world example A typed collections library implements __class_getitem__ so users can write `Stack[int]` for type hints and IDE autocompletion without needing to inherit from typing.Generic explicitly.

Common follow-ups: How does this differ from typing.Generic's __class_getitem__?;Why was this added in PEP 560?