python how to get name of the enum
Solution 1
I suspect that what's happened is that you're using the outdated pip-installable library called enum. If you did, you'd get something like
>>> from enum import Enum
>>> class testEnum(Enum):
... Code_1 = "successful response"
... Code_2 = "failure response"
...
>>> testEnum.Code_1
'successful response'
>>> testEnum.Code_1.name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'name'
whereas with the "real" enum (either enum
in the standard library if you're using modern Python, or the enum34
backport if you're not), you'd see
>>> from enum import Enum
>>> class testEnum(Enum):
... Code_1 = "successful response"
... Code_2 = "failure response"
...
>>> testEnum.Code_1
<testEnum.Code_1: 'successful response'>
>>> testEnum.Code_1.name
'Code_1'
You can confirm this independently by typing help(enum)
and seeing whether you see "NAME / enum / MODULE REFERENCE / https://docs.python.org/3.6/library/enum" (as you should) or simply "NAME / enum - Robust enumerated type support in Python" if you're using the older one.
Solution 2
You can start your investigation with the __dict__
that comes with your object. Interesting reading is found with
print(testEnum.__dict__)
In that dict you will see a good start which you can test with the following:
print(testEnum._member_names_)
which, indeed, yields
['Code_1', 'Code_2']
Solution 3
in python3.9 can use:
testEnum.__members__
Solution 4
dir(testEnum) will give you the dictionary keys.
e.g.
dir(testEnum)
returns:
['Code_1', 'Code_2', 'class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref']
Hary
Updated on June 27, 2022Comments
-
Hary almost 2 years
I have an enum like this
class testEnum(Enum): Code_1 = "successful response" Code_2 = "failure response"
Then I have a method that takes the enum key name
Code_1
and enum key valuesuccessful response
as inputs.If I send
testEnum.Code_1
then that resolves tosuccessful response
and notCode_1
.I checked some documentation online that suggests to use
testEnum.Code_1.name
but that throws an error saing that 'name' doesn't exist for the enum item.Does anyone know how to get the name of the enum key ?