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
source
share