__class_getitem__
- Python course
- Expert
- Lesson 4/47
- 5 min
Learn generic classes with __class_getitem__.
What is __class_getitem__?
__class_getitem__ lets a class itself accept subscripting. When you write Vector[int] Python calls Vector.__class_getitem__(int).
This method usually returns a generic alias. Python 3.12 supports this on type already; you can add it to your own classes too. The return value can be a string, a tuple or a types.GenericAlias. This keeps type hints and generic APIs natural.
Returning a generic alias
The return value of __class_getitem__ is up to you. The most common choice is a string like f"{cls.__name__}[{item.__name__}]"; it is readable for debugging and logging.
A more formal approach uses types.GenericAlias(cls, item). This is the same type that list[int] returns and stays compatible with type checkers. Which one you choose depends on whether your tool serves the type system or just display.
Practice Add __class_getitem__ to Vector
Write a Vector class. Add a __class_getitem__(cls, item) method that returns the string f"{cls.__name__}[{item.__name__}]". Print the result of Vector[int].
Starter code
# Add __class_getitem__ to Vector
# print the subscript callSample solution
# Add __class_getitem__ to Vector
class Vector:
def __class_getitem__(cls, item):
return f"{cls.__name__}[{item.__name__}]"
print(Vector[int])Expected output
Vector[int]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Class[key] call?
class Vector:
def __class_getitem__(cls, item):
return item
print(Vector[int])- __class_getitem__(cls, key) Correct answer
- type(key)
- __init__(key)
- __getitem__(self, key)
Explanation: answer: __class_getitem__(cls, key). Class-level subscripting calls this method.
2 Complete the __class_getitem__ definition
def __class_getitem__(cls, ____):
return f"Vector[{item.__name__}]"
def __class_getitem__(cls, item):
return f"Vector[{item.__name__}]"
Explanation: The item parameter receives the value inside the brackets.
3 Match __class_getitem__ concepts
| Term | Meaning |
|---|---|
__class_getitem__ |
Class subscript |
cls |
The class itself |
item |
Inside the brackets |
GenericAlias |
Formal type |