I have an enum defined like this:
def enum(**enums):
return type('Enum', (), enums)
Status = enum(
STATUS_OK=0,
STATUS_ERR_NULL_POINTER=1,
STATUS_ERR_INVALID_PARAMETER=2)
I have a function that returns status as Status
enum.
How can I get the name of the enum value, and not just value?
>>> cur_status = get_Status()
>>> print(cur_status)
1
I would like to get STATUS_ERR_NULL_POINTER
, instead of 1
You'd have to loop through the class attributes to find the matching name:
The generator expression loops over the attributes and their values (taken from the dictionary produced by the
vars()
function) then returns the first one that matches the value1
.Enumerations are better modelled by the
enum
library, available in Python 3.4 or as a backport for earlier versions:giving you access to the name and value:
You don't need to loop through the Enum class but just access _member_map_.