I wanted to implement a class constant in an Enum using a descriptor with a type hint that mypy would recognize. My first step was trying the docs Simple example: A descriptor that returns a constant.
class Ten:
def __get__(self, obj, objtype=None) -> int:
return 10
class A:
x = 5 # Regular class attribute
y = Ten() # Descriptor instance
reveal_type(A.x) # Revealed type is "builtins.int"
reveal_type(A.y) # Revealed type is "builtins.int"
Afterwards, applying the above simple example to an Enum has mypy recognize the type as a Literal
instead of an int
:
Revealed type is "Literal[my_module.B.y]?"
from enum import Enum
class Ten:
def __get__(self, obj, objtype=None) -> int:
return 10
class B(Enum):
One = 1
Two = 2
y = Ten() # Descriptor instance
reveal_type(B.y) # Revealed type is "Literal[my_module.B.y]?"
Am I doing something wrong or Is this a mypy bug? If it's a bug is there a workaround?