从多个值python中获取Enum名称

Ruv*_*aba 9 python enums multiple-value

我试图获得枚举的名称,给出其多个值之一:

class DType(Enum):
    float32 = ["f", 8]
    double64 = ["d", 9]
Run Code Online (Sandbox Code Playgroud)

当我试图得到一个值给它的名字时它起作用:

print DType["float32"].value[1]  # prints 8
print DType["float32"].value[0]  # prints f
Run Code Online (Sandbox Code Playgroud)

但是当我尝试从给定值中获取名称时,只会出现错误:

print DataType(8).name
print DataType("f").name
Run Code Online (Sandbox Code Playgroud)

提高ValueError("%s不是有效的%s"%(值,cls.名称))

ValueError:8不是有效的DataType

ValueError:f不是有效的DataType

有没有办法做到这一点?或者我使用了错误的数据结构?

Eth*_*man 16

最简单的方法是使用aenum1,它看起来像这样:

from aenum import MultiValueEnum

class DType(MultiValueEnum):
    float32 = "f", 8
    double64 = "d", 9
Run Code Online (Sandbox Code Playgroud)

并在使用中:

>>> DType("f")
<DType.float32: 'f'>

>>> DType(9)
<DType.double64: 'd'>
Run Code Online (Sandbox Code Playgroud)

如您所见,列出的第一个值是规范值,并显示在repr().

如果你想要显示所有可能的值,或者需要使用stdlib Enum(Python 3.4+),那么这里找到答案是你想要的(也将使用aenum)的基础:

class DType(Enum):
    float32 = "f", 8
    double64 = "d", 9

    def __new__(cls, *values):
        obj = object.__new__(cls)
        # first value is canonical value
        obj._value_ = values[0]
        for other_value in values[1:]:
            cls._value2member_map_[other_value] = obj
        obj._all_values = values
        return obj

    def __repr__(self):
        return '<%s.%s: %s>' % (
                self.__class__.__name__,
                self._name_,
                ', '.join([repr(v) for v in self._all_values]),
                )
Run Code Online (Sandbox Code Playgroud)

并在使用中:

>>> DType("f")
<DType.float32: 'f', 8>

>>> Dtype(9)
<DType.float32: 'f', 9>
Run Code Online (Sandbox Code Playgroud)

1披露:我是Python stdlibEnum,enum34backportAdvanced Enumeration(aenum) 库的作者.

  • @Rotareti:很难说。拥有现实世界的用例将有助于证明这种需求,但即便如此,“Enum”也只是作为一个构建块,而不是一整套全面的解决方案。 (2认同)
  • 如何得到“8”或“9”? (2认同)