How to get all values from python enum class?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 How To Get All Values From Python Enum Class?
00:19 Accepted Answer Score 76
00:33 Answer 2 Score 1007
00:42 Answer 3 Score 45
01:04 Answer 4 Score 167
01:27 Thank you
--
Full question
https://stackoverflow.com/questions/2950...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #enums
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Light Drops
--
Chapters
00:00 How To Get All Values From Python Enum Class?
00:19 Accepted Answer Score 76
00:33 Answer 2 Score 1007
00:42 Answer 3 Score 45
01:04 Answer 4 Score 167
01:27 Thank you
--
Full question
https://stackoverflow.com/questions/2950...
--
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')]