11

There have been a few questions on how to implement enums in Python. Most solutions end up being more or less equivalent to something like this:

class Animal:
    DOG=1
    CAT=2

Others have suggest more complicated ways of constructing enums, but ultimatly the tend to look like this example when all is said and done.

Based on my experience in Java and C#, I can think of all sorts of uses for such an idiom. However, it doesn't seem to be very Pythonic. In fact, it seems that every time somebody asks why there aren't enums in Python you tend to get a bit of a groan with canned responses about how there is no reason to try and enforce compile time type safety in a language like Python, or how designs which require enums are bad smells in Python.

My question is not how to implement enums in Python, but how in general people approach solutions to problems that lend themselves to enums in a Pythonic way. In other words, how would you solve a problem which lends itself to having a data type with a discrete set of possible values without porting your Java/C# solution to Python.

2
  • 2
    I don't see why the example you gave is un-Pythonic. And if I were implementing a state machine I'd take advantage of functions being objects and define my states as functions. Oct 10, 2012 at 2:14
  • I don't know as there is anything particularly wrong about how the enum was implemented, but I just get the feeling that some people in the Python community consider solutions which require enums in the first place to be un-Pythonic. Your suggestion that a state machine be implemented using first class functions as state is a good start to an answer though!
    – jlund3
    Oct 10, 2012 at 2:22

4 Answers 4

5

PEP 435 was just accepted, which adds the enum package to the standard library along with the Enum class and other derivatives like the IntEnum. This means that starting with Python 3.4, the "pythonic" way to use enums in a design is with this package. It will look something like this:

>>> from enum import Enum
>>> class Color(Enum):
...    red = 1
...    green = 2
...    blue = 3

>>> print(Color.red)
Color.red

>>> print(Color.red.name)
red

>>>> for color in Color:
....     print(color)
Color.red
Color.green
Color.blue

The key feature of this design is that keys can reject comparison where it doesn't make sense (unlike the string keys suggested in other answers), allow keys to have pretty printing unrelated to the key value, as well as giving the key values special properties by defining methods on the Enum subclass, in addition to the property of throwing an explicit and understandable error should the user try to use an illegal key from the Enum class.

2
  • Only drawback is: does not work before Python 3.4, which is in no major distro by now (Oct 2013). So let's wait and drink tea.
    – nerdoc
    Oct 31, 2013 at 19:14
  • 1
    A backport of PEP 435 for Python 2.4+ is available on PyPI as enum34. Although it is unofficial, it is authored by PEP 435 co-author Ethan Furman.
    – tawmas
    Jan 27, 2014 at 23:57
3

Since Python strings are immutable (and Python interns them as it sees necessary), there's not really a specific advantage to using numeric enums for sets of things. Instead, you can simply use a frozenset or tuple of strings (depending on whether you care about ordering).

If, on the other hand, what you care about is namespacing, making things attributes of a class works just fine.

As mentioned in the comments, if you're looking for something like a state machine implementation, first-class functions are your friend.

2
2

Having not come from a C# or Java background I still don't quite understand this interest in enums.

From what I understand, I would probably fall back to the django style, by putting any necessary constants in a settings file and importing where necessary.

settings.py/animals.py

DOG = 1
CAT = 2

other file:

from animals import CAT, DOG

or even...

settings.py

ANIMALS = { "DOG": 1, "CAT": 2}

other file:

from settings import ANIMALS

my_animal = "FROG"
if my_animal not in ANIMALS.keys():
    print "new species discovered!"
5
  • 2
    if my_animal not in ANIMALS.keys(): is actually (a) longer and (b) less efficient, than the simpler check if my_animal not in ANIMALS.
    – Amber
    Oct 10, 2012 at 2:29
  • 2
    I think this example highlights why people with exposure to Java/C# want enums in Python. It is one thing to accept duck typing where anything that knows how to quack is accepted. It is an entirely different matter (to a Java/C# guy) to say that your language allows simple typos to screw you over. For example, suppose I typed my_animal = "dog" instead of my_animal = "DOG" and somehow discovered a new species? Having an enum where you can just say my_animal = Animal.DOG saves you a bit of pain since you'll get an AttributeError in your face at run time rather than a discovered species bug.
    – jlund3
    Oct 10, 2012 at 2:32
  • True, I just like to show explicitly what is being done, as new comers my not be clear what is being done in the alternative.
    – monkut
    Oct 10, 2012 at 2:32
  • @jlund3 again, I'm still not clear on the need, but when programming in python I strongly recommend using pylint (or equivalent code analyzer), as this does a good job nullifying any typo issues, and writing unittests.
    – monkut
    Oct 10, 2012 at 2:39
  • @monkut: it's not even necessary to manually create a dict to get the same convenience of keys comparison because a module will create one for you; with your initial example you could do my_animal in animals.__dict__. Oct 10, 2012 at 4:32
-1

I don't believe in Enums in C#. For the State-Machine you have the Strategy pattern. Rather than looking at the state of an object and deciding what to do. Encapsulate the logic of what to do in the object itself.

This is a natural approach in Python and the introduction of enums to me is just encouraging bad code.

5
  • The question is not talking specially about state machines. I agree that in both C# and Python enums are not the way to go about implementing a state machine. However, we are instead talking about representing a type which has a small set of named values it can take on. For problems which involve that sort of data type, enums are quite useful.
    – jlund3
    Oct 1, 2014 at 21:53
  • To me that sounds like inheritance. A type which has a small set of named values. Again, python got it right the first time by not including enums. Oct 2, 2014 at 16:38
  • Using inheritance to create multiple datatypes with the same parent class is not the same thing as having a single datatype with a small set of possible values...
    – jlund3
    Oct 3, 2014 at 21:06
  • Truth be told it is. Let's say your base type has a virtual Execute() (which all children can override...of course in python everything's virtual). When you call Execute on an instance of your base class, behind the scenes the compiler looks up the Vtable and calls the appropriate function based on the instance. Basically it's a switch/case that's handled by the compiler. Which is what most enums are used for anyway. Essentially, if you give me a use case for enums, I can give you a more elegant solution using pure O-O. Oct 4, 2014 at 20:04
  • The failure of enums is that they are just data...no logic. You might as well be using C if you're going to separate logic from your data. Oct 4, 2014 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.