[Python-ideas] adopt an enum type for the standard library?

Tal Einat taleinat at gmail.com
Wed Jan 23 15:36:26 CET 2008


Christian Heimes wrote:
> Mark Summerfield wrote:
> > There is an enum module in PyPI
> > http://pypi.python.org/pypi/enum/
> > and there are several versions in the Python Cookbook.
> >
> > Wouldn't one of these be worth adopting for the standard library?
>
>
> It might be worth adding an enum to Python 2.6. I'm +0 on it.
>
> The enum implementation from pypi is not sufficient for Python core. I
> don't like its __cmp__ and __hash__ code. I also miss the feature to set
> a start value or to skip values:
>
> >>> enum = Enum("error=-1", "ok", "also_ok", "someother=1000", "last")
> >>> enum.error
> -1
> >>> enum.ok
> 0
> >>> enum.also_ok
> 1
> >>> enum.someother
> 1000
> >>> enum.last
> 1001
>
> Christian


-1 on adding a specific construct for enums.


What I usually do in Python is this:

ERROR, OK, ALSO_OK = range(-1, -1 + 3)

Start and stop values, as well step sizes other than one, are easily
achieved. Skipping values is done like this:

ERROR, OK, ALSO_OK, SOMEOTHER, LAST = range(-1, -1 + 3) + range(1000, 1000 + 2)

Updating the range(s) appropriately when adding/changing values is
easy enough. I find this solution to be good enough since the values
are not ever meant to be used explicitly, and values are not
added/changed often.

This is perhaps not very pretty or concise, but it's simple and it
only uses Python syntax and constructs which everyone knows and
understands. Readability and simplicity are usually my top concerns,
so this fits the bill.

- Tal



More information about the Python-ideas mailing list