How to get all values from python enum class?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:28 Accepted answer (Score 70)
00:47 Answer 2 (Score 820)
00:59 Answer 3 (Score 119)
01:37 Answer 4 (Score 86)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/2950...
Accepted answer links:
[IntEnum]: https://docs.python.org/3/library/enum.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #enums
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:28 Accepted answer (Score 70)
00:47 Answer 2 (Score 820)
00:59 Answer 3 (Score 119)
01:37 Answer 4 (Score 86)
02:20 Thank you
--
Full question
https://stackoverflow.com/questions/2950...
Accepted answer links:
[IntEnum]: https://docs.python.org/3/library/enum.h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #enums
#avk47
ANSWER 1
Score 1007
You can do the following:
[e.value for e in Color]
ANSWER 2
Score 167
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']
ACCEPTED ANSWER
Score 76
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]
ANSWER 4
Score 45
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')]