Python etc / __class_getitem__ (PEP-560)

Published: 12 November 2020, 18:00

PEP-560 (landed in Python 3.7) introduced a new magic method __class_getitem__. it is the same as __getitem__ but for not instancinated class. The main motivation is easier type annotation support for generic collections like List[int] or Type[Dict[str, int]]:

class MyList:
  def __getitem__(self, index):
    return index + 1

  def __class_getitem__(cls, item):
    return f"{cls.__name__}[{item.__name__}]"

MyList()[1]
# 2

MyList[int]
# 'MyList[int]'