I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
I'm mainly a C# developer, but I'm currently working on a project in Python.
How can I represent the equivalent of an Enum in Python?
An Enum class can be a one-liner.
How to use it (forward and reverse lookup, keys, values, items, etc.)
This solution is a simple way of getting a class for the enumeration defined as a list (no more annoying integer assignments):
enumeration.py:
example.py:
I really like Alec Thomas' solution (http://stackoverflow.com/a/1695250):
It's elegant and clean looking, but it's just a function that creates a class with the specified attributes.
With a little modification to the function, we can get it to act a little more 'enumy':
This creates an enum based off a specified type. In addition to giving attribute access like the previous function, it behaves as you would expect an Enum to with respect to types. It also inherits the base class.
For example, integer enums:
Another interesting thing that can be done with this method is customize specific behavior by overriding built-in methods:
Python doesn't have a built-in equivalent to
enum
, and other answers have ideas for implementing your own (you may also be interested in the over the top version in the Python cookbook).However, in situations where an
enum
would be called for in C, I usually end up just using simple strings: because of the way objects/attributes are implemented, (C)Python is optimized to work very fast with short strings anyway, so there wouldn't really be any performance benefit to using integers. To guard against typos / invalid values you can insert checks in selected places.(One disadvantage compared to using a class is that you lose the benefit of autocomplete)
On 2013-05-10, Guido agreed to accept PEP 435 into the Python 3.4 standard library. This means that Python finally has builtin support for enumerations!
There is a backport available for Python 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4. It's on Pypi as enum34.
Declaration:
Representation:
Iteration:
Programmatic access:
For more information, refer to the proposal. Official documentation will probably follow soon.
The typesafe enum pattern which was used in Java pre-JDK 5 has a number of advantages. Much like in Alexandru's answer, you create a class and class level fields are the enum values; however, the enum values are instances of the class rather than small integers. This has the advantage that your enum values don't inadvertently compare equal to small integers, you can control how they're printed, add arbitrary methods if that's useful and make assertions using isinstance:
A recent thread on python-dev pointed out there are a couple of enum libraries in the wild, including: