Is enum iteration order guaranteed?
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  backport), the order is either by value if possible, or alphabetical if not -- unless you use the _order_ attribute to set it:
_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?
> although maybe
> from MarxBros import *
> would be more familiar syntax :-)
Or you can do globals().update(MarxBros.__members__).
More information about the Python-list