键入 enum.IntEnum Class 的提示

Type Hints For enum.IntEnum Class

我正在尝试向自定义 enum.IntEnum with a particular starting value and attributes (discussed ) 添加类型提示。这对我来说似乎是正确的,但对 mypy.

却不是
from __future__ import annotations
import enum
import itertools

counter = itertools.count(42)

class Goo(enum.IntEnum):
   MOO = ("grr", 1.2)
   LOO = ("fzz", 3.4)

   def __new__(cls,label: str, size: float) -> Goo:
      value = next(counter)

      member = int.__new__(cls, value)

      member._value_ = value          # 16
      member.label   = label          # 17
      member.size    = size           # 18

      return member

assert isinstance(Goo.MOO, Goo)
assert isinstance(Goo.MOO, int)
assert Goo.MOO       == 42
assert Goo.MOO.label == "grr"         # 25
assert Goo.MOO.size  == 1.2           # 26

程序如图所示运行,但是 mypy 给我这些错误,我不知道如何修复。我认为第一个来自于我在 mypy 已经确定它是什么之后更改 _value_ 的类型,我认为没有办法改变它的想法。我不明白其他人,这意味着我无法向我自己的 class.

添加属性
% mypy goo
goo:16: error: Incompatible types in assignment (expression has type "int", variable has type "Tuple[str, float]")
goo:17: error: "Goo" has no attribute "label"
goo:18: error: "Goo" has no attribute "size"
goo:25: error: "Goo" has no attribute "label"
goo:26: error: "Goo" has no attribute "size"

正确的做法是什么?

可能有更好的方法,但静态地为两个属性提供提示似乎就足够了。

class Goo(enum.IntEnum):
   label: str
   size: float

   ...