惯用方法检查一个值是否在枚举内部

发布于 2025-02-14 00:27:07 字数 661 浏览 0 评论 0 原文

我想检查某些枚举的值集中是否存在一些字符串值。这是我要做的:

from enum import Enum

class Color(str, Enum):

    RED = "red"
    GREEN = "green"
    YELLOW = "yellow"

s = "red"
# s = "blue"

if any(s == c.value for c in Color):
    print(Color(s))

当我检查文档发现:

Enummeta Metaclass负责提供包含(), dir (), iter ()和其他允许一个人可以允许的方法用典型类失败的枚举类做事,例如list(color)或some_enum_var in Color

但我想要一些不同的东西(检查存在 values )。是否有一种解决这个问题的方法?

I want to check if some string value exists in the values set of some Enum. Here is what I do:

from enum import Enum

class Color(str, Enum):

    RED = "red"
    GREEN = "green"
    YELLOW = "yellow"

s = "red"
# s = "blue"

if any(s == c.value for c in Color):
    print(Color(s))

When I checked the documentation I found that:

The EnumMeta metaclass is responsible for providing the contains(), dir(), iter() and other methods that allow one to do things with an Enum class that fail on a typical class, such as list(Color) or some_enum_var in Color

But I want something different (checking existence for values). Is there a more pythonic way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

三寸金莲 2025-02-21 00:27:07

3.12中

>>> "red" in Color
<stdin>:1: DeprecationWarning: in 3.12 __contains__ will no longer raise TypeError, but will return True if
obj is a member or a member's value
...
TypeError: unsupported operand type(s) for 'in': 'str' and 'EnumMeta'

在Python 该构造函数,如果有匹配值,它将返回适当的枚举实例,否则 valueerror 否则。

>>> Color("red")
<Color.RED: 'red'>
>>> Color("asdf")
Traceback (most recent call last):
...
ValueError: 'asdf' is not a valid Color

In Python 3.12 you'll be able to do this directly with in:

>>> "red" in Color
<stdin>:1: DeprecationWarning: in 3.12 __contains__ will no longer raise TypeError, but will return True if
obj is a member or a member's value
...
TypeError: unsupported operand type(s) for 'in': 'str' and 'EnumMeta'

While we're waiting for that, though, one option in addition to the one you've already found is to pass your value to the constructor, which will return the appropriate enum instance if there's a matching value, and raise ValueError otherwise.

>>> Color("red")
<Color.RED: 'red'>
>>> Color("asdf")
Traceback (most recent call last):
...
ValueError: 'asdf' is not a valid Color
一笔一画续写前缘 2025-02-21 00:27:07

您可以针对 _value2member_map _ 测试值,如果您不希望用 enum enum sub-class,将值映射到成员类> try-except 块:

if s in Color._value2member_map_:
    print(Color(s))

You can test values against _value2member_map_, a dict attribute of the Enum sub-class that maps values to member classes, if you prefer not to clutter up your code with a try-except block:

if s in Color._value2member_map_:
    print(Color(s))
凉薄对峙 2025-02-21 00:27:07

这是基于 blhsing 的答案:

from enum import Enum

class Color(str, Enum):

    RED = "red"
    GREEN = "green"
    YELLOW = "yellow"

    @staticmethod
    def values():
        # provide a meaningful named getter
        return Color._value2member_map_

s = "green"
# s = "blue"

# actual use becomes more clear
if s in Color.values():
    print(Color(s))

Here is a slightly more aesthetic implementation based on blhsing's answer:

from enum import Enum

class Color(str, Enum):

    RED = "red"
    GREEN = "green"
    YELLOW = "yellow"

    @staticmethod
    def values():
        # provide a meaningful named getter
        return Color._value2member_map_

s = "green"
# s = "blue"

# actual use becomes more clear
if s in Color.values():
    print(Color(s))
绝影如岚 2025-02-21 00:27:07

只需将其转换为价值清单并检查

"red" in [item.value for item in Color]

Just convert it into value list and check

"red" in [item.value for item in Color]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文