The least informal enumeration support in python2.7 - flufl.enum or enum34?

I never thought I needed to do this, but here I intend to use enums in python 2.7.

There is Barry flufl.enum , which PEP 435 says: "... was the reference implementation on which this PEP was originally based."

But there is also backport enum34 on pypi .

Both of these seem semi-official, and which one should be used in the new code?

β€œThere must be one obvious way to do this,” but this is a difficult topic for Google because there are dozens (hundreds?) Of manual implementations there. And python 3.4 enum is still a candidate for release.

I tried both flufl.enum.Enum and enum34.Enum , and the behavior is completely different - primarily the different semantics of __getitem__ . According to this comment by Martijn Pieters, backport was / was complicated as the implementation is based on the new __prepare__ function on the metaclass. I read this post and PEP as a whole.

+7
python enums
source share
1 answer

enum34 matches what is in Python3.4 , so the one to be used.

The only big difference between backport and 3.4:

  • In Python 2, you cannot get the definition order (because __prepare__ does not exist yet), but there is a workaround - define _order_ , and that will be the "definition order" in Python 2 (it is simply ignored in Python 3). If you are not using a workaround, the order used is the member values ​​in ascending order.

Update

  • preferred spelling is now _order_ (single, not double leading and ending underscores)

  • Python3.6 + will verify that _order_ matches the actual order (useful for synchronizing Python 2/3 code)


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

+10
source share

All Articles