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?
Join Stack Overflow to learn, share knowledge, and build your career.
|
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? |
||||
locked by animuson♦ Jan 25 '15 at 1:44This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here |
||||
|
|
||||
|
Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as
Installing
or equivalently:
In earlier versions, one way of accomplishing enums is:
which is used like so:
You can also easily support automatic enumeration with something like this:
and used like so:
Support for converting the values back to names can be added this way:
This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw KeyError if the reverse mapping doesn't exist. With the first example:
|
|||||||||||||||||||||
|
|
Before PEP 435, Python didn't have an equivalent but you could implement your own. Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...
In Python 3.4 (PEP 435), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum values are distinct from integers.
If you don't want to type the values, use the following shortcut:
|
|||||||||||||||||||||
|
|
Here is one implementation:
Here is its usage:
|
|||||||||||||||||||||
|
|
If you need the numeric values, here's the quickest way:
In Python 3.x you can also add a starred placeholder at the end, which will soak up all the remaining values of the range in case you don't mind wasting memory and cannot count:
|
||||
|
|
|
The best solution for you would depend on what you require from your fake Simple enum: If you need the
Using a
In addition to the above, if you also require that the items belong to a container of some sort, then embed them in a class:
To use the enum item, you would now need to use the container name and the item name:
Complex enum: For long lists of enum or more complicated uses of enum, these solutions will not suffice. You could look to the recipe by Will Ware for Simulating Enumerations in Python published in the Python Cookbook. An online version of that is available here. More info: PEP 354: Enumerations in Python has the interesting details of a proposal for enum in Python and why it was rejected. |
|||||
|
|
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:
|
|||||||||||||||||||||
|
|
An Enum class can be a one-liner.
How to use it (forward and reverse lookup, keys, values, items, etc.)
|
|||||||||
|
|
Python doesn't have a built-in equivalent to However, in situations where an
(One disadvantage compared to using a class is that you lose the benefit of autocomplete) |
|||||||||||||
|
|
So, I agree. Let's not enforce type safety in Python, but I would like to protect myself from silly mistakes. So what do we think about this?
It keeps me from value-collision in defining my enums.
There's another handy advantage: really fast reverse lookups:
|
|||||
|
Use it like this:
if you just want unique symbols and don't care about the values, replace this line:
with this:
|
|||||||||
|
|
I prefer to define enums in Python like so:
It's more bug-proof than using integers since you don't have to worry about ensuring that the integers are unique (e.g. if you said Dog = 1 and Cat = 1 you'd be screwed). It's more bug-proof than using strings since you don't have to worry about typos (e.g. x == "catt" fails silently, but x == Animal.Catt is a runtime exception). |
||||
|
|
|
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. |
||||
|
|
|
Another, very simple, implementation of an enum in Python, using
or, alternatively,
Like the method above that subclasses
But has more flexibility as it can have different keys and values. This allows
to act as is expected if you use the version that fills in sequential number values. |
||||
|
|
|
Hmmm... I suppose the closest thing to an enum would be a dictionary, defined either like this:
or
Then, you can use the symbolic name for the constants like this:
There are other options, like a list of tuples, or a tuple of tuples, but the dictionary is the only one that provides you with a "symbolic" (constant string) way to access the value. Edit: I like Alexandru's answer too! |
|||||
|
|
What I use:
How to use:
So this gives you integer constants like state.PUBLISHED and the two-tuples to use as choices in Django models. |
||||
|
|
|
davidg recommends using dicts. I'd go one step further and use sets:
Now you can test whether a value matches one of the values in the set like this:
like dF, though, I usually just use string constants in place of enums. |
|||||
|
|
This is the best one I have seen: "First Class Enums in Python" http://code.activestate.com/recipes/413486/ It gives you a class, and the class contains all the enums. The enums can be compared to each other, but don't have any particular value; you can't use them as an integer value. (I resisted this at first because I am used to C enums, which are integer values. But if you can't use it as an integer, you can't use it as an integer by mistake so overall I think it is a win.) Each enum is a unique value. You can print enums, you can iterate over them, you can test that an enum value is "in" the enum. It's pretty complete and slick. Edit (cfi): The above link is not Python 3 compatible. Here's my port of enum.py to Python 3:
|
|||||||||
|
|
From Python 3.4 there will be official support for enums. You can find documentation and examples here on Python 3.4 documentation page.
|
|||||
|
|
I have had occasion to need of an Enum class, for the purpose of decoding a binary file format. The features I happened to want is concise enum definition, the ability to freely create instances of the enum by either integer value or string, and a useful
A whimsical example of using it:
Key features:
|
|||||||||||||||||
|
|
Keep it simple:
Then:
|
||||
|
|
|
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:
|
|||||||||
|
|
The new standard in Python is PEP 435, so an Enum class will be available in future versions of Python:
However to begin using it now you can install the original library that motivated the PEP:
Then you can use it as per its online guide:
|
||||
|
|
If you name it, is your problem, but if not creating objects instead of values allows you to do this:
When using other implementations sited here (also when using named instances in my example) you must be sure you never try to compare objects from different enums. For here's a possible pitfall:
Yikes! |
||||
|
|
|
Alexandru's suggestion of using class constants for enums works quite well. I also like to add a dictionary for each set of constants to lookup a human-readable string representation. This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.
|
||||
|
|
|
The enum package from PyPI provides a robust implementation of enums. An earlier answer mentioned PEP 354; this was rejected but the proposal was implemented http://pypi.python.org/pypi/enum. Usage is easy and elegant:
|
||||
|
|
|
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:
|
|||||
|
|
While the original enum proposal, PEP 354, was rejected years ago, it keeps coming back up. Some kind of enum was intended to be added to 3.2, but it got pushed back to 3.3 and then forgotten. And now there's a PEP 435 intended for inclusion in Python 3.4. The reference implementation of PEP 435 is As of April 2013, there seems to be a general consensus that something should be added to the standard library in 3.4—as long as people can agree on what that "something" should be. That's the hard part. See the threads starting here and here, and a half dozen other threads in the early months of 2013. Meanwhile, every time this comes up, a slew of new designs and implementations appear on PyPI, ActiveState, etc., so if you don't like the FLUFL design, try a PyPI search. |
||||
|
|
|
Here's an approach with some different characteristics I find valuable:
and most importantly prevents comparisons between enums of different types! Based closely on http://code.activestate.com/recipes/413486-first-class-enums-in-python. Many doctests included here to illustrate what's different about this approach.
|
||||
|
|
|
I had need of some symbolic constants in pyparsing to represent left and right associativity of binary operators. I used class constants like this:
Now when client code wants to use these constants, they can import the entire enum using:
The enumerations are unique, they can be tested with 'is' instead of '==', they don't take up a big footprint in my code for a minor concept, and they are easily imported into the client code. They don't support any fancy str() behavior, but so far that is in the YAGNI category. |
|||||
|
|
Here is a variant on Alec Thomas's solution:
|
||||
|
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?