Yet Another Python Enum Module

I didn't like the existing enum recipes, so I cooked up what I feel is a better way of working with enumerations in python. The result is yapyenum, hosted on github. Rather than come up with something new to say about it, I'll just repost the README here:

This module provides named enumerations for python.

Unlike other implementations that I have seen, this is not an anonymous enumeration. To use it derive from the Enumeration class provided in and list the names of the enum members in the class member enum.

The enum is itself a singleton class. It tries to be immutable via slots and by refusing to allow its members to be changed.

Enum members are an integer subclass with a "name" property and that knows how to pretty print itself. The enum values are interchangeable with integers, which may or may not be what you want.

The class supports membership ("FOO in MyEnum") and mapping a non-instance-member value to a name. (I.e. if FOO uses the integer value 1, then returns "FOO".)

Tested on 2.4.6, 2.5.2, 2.6.2, on a combination of debian sarge, etch, lenny, and ubuntu 9.04.

There are obvious capabilities that could be added but this does all that I need so far. Patches will be happily accepted.

Permissive license (MIT). Have fun.

For other enum recipes, see:

Several of these recipes have comments along the lines of "if you're using one of these too-fancy enum recipes in python, you're doing something unpythonic". This is likely true, but sometimes unavoidable for social, political, and/or historical reasons.

Posted on 2009-07-19 by brian in python .


Overall this looks pretty nice. I think I would choose a nicer (aesthetically) name for 'enum' ('names' or just 'enum', perhaps), but that's a minor qualm. Not sure if I would actually use your class here (for the reason listed, it seems too complex for most Pythonic needs), but I'll try to keep in mind should the need arise.

Max Battcher
2009-07-20 03:15:29

Max: Thanks for the comment. You're right that "enum" is ugly. If/when I spin another version I'll probably change it as you suggested.

Brian St. Pierre
2009-07-20 11:25:10
Comments on this post are closed. If you have something to share, please send me email.