如何检查字符串枚举中是否存在字符串?

科宝

我创建了以下枚举:

from enum import Enum

class Action(str, Enum):
    NEW_CUSTOMER = "new_customer"
    LOGIN = "login"
    BLOCK = "block"

我也继承自str,所以我可以做以下事情:

action = "new_customer"
...
if action == Action.NEW_CUSTOMER:
    ...

我现在希望能够检查此Enum中是否有字符串,例如:

if "new_customer" in Action:
    ....

我尝试将以下方法添加到类中:

def __contains__(self, item):
    return item in [i for i in self]

但是,当我运行此代码时:

print("new_customer" in [i for i in Action])
print("new_customer" in Action)

我得到这个异常:

True
Traceback (most recent call last):
  File "/Users/kevinobrien/Documents/Projects/crazywall/utils.py", line 24, in <module>
    print("new_customer" in Action)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 310, in __contains__
    raise TypeError(
TypeError: unsupported operand type(s) for 'in': 'str' and 'EnumMeta'
彼得·D

今天我碰到了这个问题。我不得不为Python 3.8更改许多子包。

也许是以下其他解决方案的替代方案,其灵感来自此处对类似问题的出色答案以及此页面上@MadPhysicist的答案

class MetaEnum(EnumMeta):
    def __contains__(cls, item):
        try:
            cls(item)
        except ValueError:
            return False
        return True    


class BaseEnum(Enum, metaclass=MetaEnum):
    pass


class Stuff(BaseEnum):
    foo = 1
    bar = 5

测试(在py37或38中):

>>> 1 in Stuff
True

>>> Stuff.foo in Stuff
True

>>> 2 in Stuff
False

>>> 2.3 in Stuff
False

>>> 'zero' in Stuff
False

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何检查字符串中是否存在“#”标签?

如何检查字符串VBA中是否存在“ \”?

如何检查字符串中是否存在行?

如何检查字符串中是否存在“ @”

如何检查字符串中是否存在字符串?

如何检查字符串列表及其索引中是否存在特定字符串

如何检查字符串枚举数组是否包含字符串

如何使用beautifulsoup检查字符串是否存在

检查字符串中是否存在列表元素

检查字符串中是否存在模式

检查字符串中是否存在星号

VBA - 检查字符串中是否存在“逗号”

如何检查字符串数组中是否存在字符?

如何检查字符数组数组中是否存在字符串

如何使用javascript检查字符串中是否存在带字符的新行?

检查字符串数组中是否存在字符串的有效方法

如何检查字符串列表中的任何字符串是否是字符串的子字符串?

如何从HTML标记代码中获取特定字符串并检查字符串中是否存在<img>标记?

如何检查是否给定的字符串键枚举存在

如何使用JavaScript检查字符串中的子字符串后是否存在数字?

在Java中,如何检查字符串是否是回文?

如何检查字符串是否在text []中?

如何检查字符串是否是 Python 中的数字?

如何使用C中的strstr()函数检查字符串中是否存在char

如何检查字符串是否在pandas DataFrame中较长的字符串中?

如何检查给定的字符串在Typescript中的字符串枚举中是否作为值存在?

如何检查字符串中是否存在数组值之一?

如何检查字符串中特定点的数字是否存在?

如何使用lodash js检查字符串是否存在于数组中?