Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python how to get name of the enum

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 value successful response as inputs.

If I send testEnum.Code_1 then that resolves to successful response and not Code_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 ?

like image 328
Hary Avatar asked Jun 08 '17 23:06

Hary


2 Answers

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.

like image 68
DSM Avatar answered Sep 21 '22 22:09

DSM


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']
like image 39
Shawn Mehan Avatar answered Sep 21 '22 22:09

Shawn Mehan