I've been messing around with python's enum library and have come across a conundrum. In the docs, they show an example of an auto-numbering enum, wherein something is defined:
class Color(AutoNumber):
red = ()
green = ()
...
I want to make a similar class, but the value would automatically be set from the name of the member AND keep the functionality that you get from doing the str
and enum
mixin stuff
So something like:
class Animal(MagicStrEnum):
horse = ()
dog = ()
Animal.dog == 'dog' # True
I've looked at the source code of the enum module and tried a lot of variations messing around with __new__
and the EnumMeta
class
Update: 2017-03-01
Original answer
The difficulty with an
AutoStr
class is that the name of the enum member is not passed into the code that creates it, so it is unavailable for use. Another wrinkle is thatstr
is immutable, so we can't change those types of enums after they have been created (by using a class decorator, for example).The easiest thing to do is use the Functional API:
which gives us:
The next easiest thing to do, assuming you want to make a base class for your future enumeration use, would be something like my
DocEnem
:and in use:
Note that unlike the first option,
DocEnum
members are notstr
s.If you want to do it the hard way: subclass
EnumMeta
and fiddle with the newEnum
's class dictionary before the members are created:Which gives us:
1 Disclosure: I am the author of the Python stdlib
Enum
, theenum34
backport, and the Advanced Enumeration (aenum
) library.Perhaps you are looking for the
name
attribute which is automatically provided by theEnum
classThough if you really want to shoot yourself in the foot. And I'm sure this will introduce a whole world of gotchas (I've eliminated the most obvious one).