How to get all values from python enum class?
You can do the following:
[e.value for e in 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']
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]
To use Enum with any type of value, try this:
Updated with some improvements... Thanks @Jeff, by your tip!
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 'GREEN'
BLUE = ('blue', '#0000ff')
@staticmethod
def list():
return list(map(lambda c: c.value, Color))
print(Color.list())
As result:
[1, 'GREEN', ('blue', '#0000ff')]