Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Future-compatible enums in 2.7?

Tags:

python

enums

Many methods of implementing enums are shown in the answers to this question. However, PEP0435 is out now and describes how Enum and IntEnum will become official in Python 3.4.

My question is not about the advantages/disadvantages of particular ways of simulating enums in Python. Rather I'd like advice on the most forward-compatibile way for those of us still stuck in 2.X releases.

flufl.enum was originally going to be the reference implementation but was dropped due to members not being instances of the type (and of allowing subclasses with additional members at the same time). The latter wouldn't affect much day-to-day but perhaps the former would cause more issues?

Are there any libraries out there that more closely resemble what is being added to 3.4 and are compatible with 2.7+?

like image 239
ShawnFumo Avatar asked May 20 '13 15:05

ShawnFumo


People also ask

Can enum have multiple values Python?

Enums can't have multiple value per name.

Is there an enum in Python?

Enum is a class in python for creating enumerations, which are a set of symbolic names (members) bound to unique, constant values. The members of an enumeration can be compared by these symbolic anmes, and the enumeration itself can be iterated over.

Should enums be capitalized Python?

Notice that enumerations are not normal Python classes, even though they are defined in a similar way. As enumerations are meant to represent constant values, it is advisable to uppercase the enum member names.

How do you convert enum to int in Python?

Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.


1 Answers

There is a backport of the PEP 435 enum module available on PyPI as enum34. The backport seems to be unofficial, however it is authored by Ethan Furman, who is a Python core committer and one of the co-authors of PEP 435.

The backport is declared compatible with Python 2.4 and greater. Of course, under Python 2 there are a few, relatively minor, differences in behaviour, but from my preliminary exploration under Pyhon 2.7, I'd say that the level of forward compatibility is quite high.

like image 151
tawmas Avatar answered Sep 21 '22 06:09

tawmas