将简单的描述符示例作为枚举类别常数与mypy

发布于 2025-02-03 02:37:16 字数 1150 浏览 4 评论 0原文

我想实现枚举中的类常数使用描述符带有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文