Python Enum Class Membership

When using the Enum class introduced in Python 3 programmatically , how should a programmer check the Enum membership of a given integer?

Obviously, you could just ask for forgiveness , but is there a membership verification function that I missed otherwise? In a more explicit form, I would like to take an integer value and check if its value matches the actual numbering.

from enum import Enum

class TestEnum(Enum):
    a = 0
    b = 1
    c = 2

Conclusion:

In [13]: TestEnum(0)
Out[13]: <TestEnum.a: 0>

In [14]: TestEnum(4)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-09c663e9e214> in <module>()
----> 1 TestEnum(4)

C:\Anaconda3\lib\enum.py in __call__(cls, value, names, module, qualname, type, start)
    239         """
    240         if names is None:  # simple value lookup
--> 241             return cls.__new__(cls, value)
    242         # otherwise, functional API: we're creating a new Enum type
    243         return cls._create_(value, names, module=module, qualname=qualname, type=type, start=start)

C:\Anaconda3\lib\enum.py in __new__(cls, value)
    474                 if member._value_ == value:
    475                     return member
--> 476         raise ValueError("%r is not a valid %s" % (value, cls.__name__))
    477
    478     def __repr__(self):

ValueError: 4 is not a valid TestEnum
+4
source share
2 answers

Enum does has a method __contains__, but it checks the names of members, not the values ​​of members:

def __contains__(cls, member):
    return isinstance(member, cls) and member._name_ in cls._member_map_

( CPython) , ( ):

>>> 2 in TestEnum._value2member_map_
True
>>> 3 in TestEnum._value2member_map_
False

, , , __members__.values():

>>> class TestEnum(Enum):
...     a = 0
...     b = 1
...     c = 2
...
...     @classmethod
...     def check_value_exists(cls, value):
...         return value in (val.value for val in cls.__members__.values())
...

>>>
>>> TestEnum.check_value_exists(2)
True
>>> TestEnum.check_value_exists(3)
False
+3

:

from enum import Enum

class TestEnum(Enum):
    a = 3
    b = 2
    c = 1


print(TestEnum.b.name,TestEnum.b.value)

print(TestEnum(2).name,TestEnum(2).value)

:

b 2

0

Source: https://habr.com/ru/post/1672447/


All Articles