How to get all values from python enum class?
You can do the following:
[e.value for e in Color]
You can use IntEnum:
from enum import IntEnum
class Color(IntEnum):
RED = 1
BLUE = 2
print(int(Color.RED)) # prints 1
To get list of the ints:
enum_list = list(map(int, Color))
print(enum_list) # prints [1, 2]
Use _member_names_
for a quick easy result if it is just the names, i.e.
Color._member_names_
Also, you have _member_map_
which returns an ordered dictionary of the elements. This function returns a collections.OrderedDict
, so you have Color._member_map_.items()
and Color._member_map_.values()
to play with. E.g.
return list(map(lambda x: x.value, Color._member_map_.values()))
will return all the valid values of Color
Based on the answer by @Jeff, refactored to use a classmethod
so that you can reuse the same code for any of your enums:
from enum import Enum
class ExtendedEnum(Enum):
@classmethod
def list(cls):
return list(map(lambda c: c.value, cls))
class OperationType(ExtendedEnum):
CREATE = 'CREATE'
STATUS = 'STATUS'
EXPAND = 'EXPAND'
DELETE = 'DELETE'
print(OperationType.list())
Produces:
['CREATE', 'STATUS', 'EXPAND', 'DELETE']