Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 400
wim Avatar asked Feb 11 '14 17:02

wim


People also ask

What is Enum34 in python?

Enum34 is the new Python stdlib enum module available in Python 3.4 backported for previous versions of Python from 2.4 to 3.3. Website: https://pypi.org/project/enum34/ License: Modified BSD. Package source: python-xyz.scm.

Does python have Enums?

Python's enum module provides the Enum class, which allows you to create enumeration types. To create your own enumerations, you can either subclass Enum or use its functional API.


1 Answers

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.

like image 75
Ethan Furman Avatar answered Sep 20 '22 16:09

Ethan Furman