Customize how a class reacts to bracket subscription with __class_getitem__().
How It Works
__class_getitem__(cls, item) runs for expressions such as Container[int] when metaclass __getitem__ does not take priority. It supports generic type notation; avoid using it to implement ordinary instance indexing.
The typing module provides established generic mechanisms for normal type annotations.
Step-by-Step Example
class Container:
def __class_getitem__(cls, item_type):
return (cls.__name__, item_type.__name__)
print(Container[int])
print(Container[str])
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
('Container', 'int')
('Container', 'str')
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Try a class that records its subscribed type in a readable descriptor.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Confusing Container[int] with instance[index] handled by __getitem__().
- Implementing a runtime type checker based only on the presence of bracket syntax.
Key Takeaways
- Customize how a class reacts to bracket subscription with __class_getitem__().
- __class_getitem__(cls, item) runs for expressions such as Container[int] when metaclass __getitem__ does not take priority.
- The typing module provides established generic mechanisms for normal type annotations.