What is the purpose of __class_getitem__ in Python and how does it enable generic type hints?

Python Professional Hard

Python Professional — Hard

What is the purpose of __class_getitem__ in Python and how does it enable generic type hints?

Key points

  • __class_getitem__ is called when a class is subscripted
  • It returns a GenericAlias or custom object
  • Enables classes to support type parameters in annotations
  • Facilitates generic type hinting in Python

Ready to go further?

Related questions