7

Never thought I'd need to do this, but here I am intending to use enums in python 2.7.

There is Barry's flufl.enum which PEP 435 says "...was the reference implementation upon which this PEP was originally based".

But there is also a backport enum34 on pypi.

These both seem semi-official, so which one should I use in new code?

"There should be one obvious way to do it", but it's a hard topic to google for because there are dozens (hundreds?) of hand-rolled implementations out there. And the python 3.4 enum is still just a release candidate.

I've tried out both flufl.enum.Enum and enum34.Enum, and the behaviour is quite different - most notably the differing semantics of __getitem__. According to this comment by Martijn Pieters, backport is/was challenging because implementation relies on the new __prepare__ function on the metaclass. I've read this post and the PEP in entirety.

wim
  • 338,267
  • 99
  • 616
  • 750

1 Answers1

10

enum34 matches what is in Python3.4, so that's the one to use.

The one big difference between the backport and 3.4's:

  • In Python 2 you cannot get definition order (because __prepare__ doesn't exist yet), but there is a work-around -- define _order_ and it will be the "definition order" in Python 2 (it's simply ignored in Python 3). If you don't use the workaround the order used is the values of the members, in increasing order.

Update

  • the preferred spelling is now _order_ (single instead of double leading and trailing underscores)

  • Python3.6+ will check that _order_ matches the actual order (useful for keeping Python 2/3 code in sync)


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

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237