>>> Example(1).name
'one'
also see the Python docs.
Answer from Nils Werner on Stack OverflowPlease help accessing Enum name and value
Why do Enums require you access the values with the 'value' keyword? The default behavior should return the value.
How to get all values from python enum class? - Stack Overflow
Find enum value by enum name in string - Python - Stack Overflow
Videos
Hello all! I wanted to use some enums in a little file I was writing, and got some weird errors, so I went to the tutorial
https://docs.python.org/3/library/enum.html#programmatic-access-to-enumeration-members-and-their-attributes
and it basically says that this should print 'RED' and 1
from enum import Enum
class Color(Enum):RED = 1GREEN = 2BLUE = 3
member = Color.REDprint(member.name)print(member.value)
but printing member.name or member.value does not work -> AttributeError: 'int' object has no attribute 'value'
What am I missing?
If I define enum:
from enum import Enum
class Enum1(Enum):
A = 1
B = 2
C = 3and then do:
a = Enum1.A print(a)
You get:
<Enum.A: 1>
Instead you need to do:
a = Enum1.A.value print(a)
To print '1'.
Why is the default behavior of 'Enum1.A' not to return the value like it is for C#, Java, and C++? This just forces me to add 6 extra characters and makes accessing enum values look uglier. It is especially problematic if I am accessing multiple enum elements on the same line, which happens if I am using enums to organize a datatable.
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']