wim wim -4 years ago 143
Python Question

Least unofficial enum support in python2.7 - flufl.enum or enum34?

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.

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download