Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Enum class membership

Tags:

python

enums

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

Obviously, you could just ask for forgiveness but is there a membership check function that I have otherwise missed? Put more explicitly, I would like to take an integer value and check to see if its value corresponds to a valid enumeration.

from enum import Enum

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

Output:

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
like image 760
Gregory Kuhn Avatar asked Mar 16 '17 09:03

Gregory Kuhn


People also ask

Can enum class have methods Python?

Customize Python enum classes Python enumerations are classes. It means that you can add methods to them, or implement the dunder methods to customize their behaviors.

What is Auto in enum Python?

Introduction to the enum auto() function In this example, we manually assign integer values to the members of the enumeration. To make it more convenient, Python 3.6 introduced the auto() helper class in the enum module, which automatically generates unique values for the enumeration members.

Should you use enums in Python?

Python enums are useful to represent data that represent a finite set of states such as days of the week, months of the year, etc. They were added to Python 3.4 via PEP 435. However, it is available all the way back to 2.4 via pypy. As such, you can expect them to be a staple as you explore Python programming.


1 Answers

Enum does have a __contains__ method, but it checks for member names rather than member values:

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

Internally(in CPython) they do have a private attribute that maps values to names(will only work for hashable values though):

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

But it's not a good idea to rely on private attributes as they can be changed anytime, hence you can add your own method that loops over __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
like image 84
Ashwini Chaudhary Avatar answered Sep 30 '22 17:09

Ashwini Chaudhary