I am modelling a problem where it doesn't make sense to have instantations of a class -- in this case the periodic table. I want to be able to index the periodic table with an int and get the associated element (from the atomic number; the element objects are stored as class variables). I can do this easily with metaclasses, but mypy doesn't like this. Here is my approach:
class PeriodicTableBase(type):
def __getitem__(cls, x: int) -> int:
return x
class PeriodicTable(metaclass=PeriodicTableBase):
pass
a = PeriodicTable[1]
and after finding PEP560:
class PeriodicTable:
def __class_getitem__(cls, x: int) -> int:
return x
a = PeriodicTable[1]
Mypy gives the same error for both of these (presumably because they collide with the way generic types are defined):
Typing.py:9: error: "PeriodicTable" expects no type arguments, but 1 given
Typing.py:9: error: Invalid type: try using Literal[1] instead?
Of course they both function at runtime.
Is there a way I can do this cleanly whilst keeping mypy happy?