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 enum.py 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 MyEnum.name(1) 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:
- PEP 354 (rejected enum proposal for python)
- The enum module in pypi
- Recipe 413486: First Class Enums in Python
- Recipe 305271: Enumerated values by name or number
- Recipe 67107: Enums for Python
- Recipe 81098: python enum with strings
- At Stack Overflow: What's the best way to implement an 'enum' in Python?
- The Python Cookbook (at page 607 on Google Books)
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.