将简单的描述符示例作为枚举类别常数与mypy
我想实现枚举中的类常数使用描述符带有Mypy可以识别的类型提示。我的第一步是尝试文档简单示例:返回常数的描述符。
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"
之后,将上述简单示例应用于枚举使MyPy识别为字面
而不是int
:
揭示的类型是“文字[my_module.by]?”
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]?"
我是做错了什么还是这是一个mypy错误?如果是错误,是否有解决方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论