Is enum iteration order guaranteed?

Ethan Furman ethan at stoneleaf.us
Tue Jan 10 00:55:10 EST 2017


On 01/09/2017 09:18 PM, Steven D'Aprano wrote:

> The docs say that enums can be iterated over, but it isn't clear to me whether
> they are iterated over in definition order or value order.
>
> If I have:
>
> class MarxBros(Enum):
>      GROUCHO = 999
>      CHICO = 5
>      HARPO = 11
>      ZEPPO = auto()
>      GUMMO = -1
>
> GROUCHO, CHICO, HARPO, ZEPPO, GUMMO = list(MarxBros)

In Python 3 it is always definition order.  In Python 2 (using the enum34 [1] backport), the order is either by value if possible, or alphabetical  if not -- unless you use the _order_ attribute to set it:

class MarkBros(Enum):
     _order_ = 'GROUCHO CHICO HARGPO ZEPPO GUMMO'
     GROUCHO = 999
     ...

> On that related note, how would people feel about a method that injects enums
> into the given namespace?
>
> MarxBros._inject_(globals())
>
> although maybe
>
> from MarxBros import *
>
> would be more familiar syntax :-)

Or you can do globals().update(MarxBros.__members__).

--
~Ethan~


More information about the Python-list mailing list