Enum auto in python2

Viewed 345

I've read that when using Enums in python 3 you have the option to use auto to automatically ennumerate the elements. It seems that in python2 this is not possible.

However I found this doc which permits auto numeration. However it is not working well

In the docs we have

class AutoNumber(Enum):
    def __new__(cls):
        value = len(cls.__members__) + 1
        obj = object.__new__(cls)
        obj._value_ = value
        return obj

class Color(AutoNumber):
    red = ()
    green = ()
    blue = ()

Then in the docs they give us as example

Color.green.value == 2

and yes, green give us 2. But red give us 3! and blue give us 1

so the elements are of value 3,2,1 and not 0,1,2 or 1,2,3 as I assumed.

I've tried to modify AutoNumber without success.

How can I get the correct numeration? (0,1,2) (1,2,3) or (-1,0,1) is ok

1 Answers

The problem you are running into is that:

  • in Python 2, dicts are not ordered
  • in Python 2, there is no __prepare__ on metaclasses (to remember the ordering for is)

If you are using Python 2 you should use the aenum library1, and specify the _order_ attribute, like so:

from aenum import Enum, auto

class Color(Enum):
    _order_ = 'red green blue'
    red = auto()
    green = auto()
    blue = auto()

In cases where you have a lot of names, you can also use the functional API form:

Color = Enum('Color', """
    red
    green
    blue
    magenta
    white
    """)

The names just need to be white-space separated, and they will be valued starting from 1.

--

1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

Related