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

Mark Summerfield mark at qtrac.eu
Thu Jan 24 11:04:06 CET 2008

On 2008-01-24, Raymond Hettinger wrote:
> [Mark Summerfeld]
> > I think enums are a common enough requirement to be worth
> >adding to the standard library---not to the language.
> -1  This is clutter.
> Also, I disagree about there being a need.  We've long been able to roll
> our own with a simple class definition (like the first example shown
> below), but people rarely do that.  They don't want to pay the cost in
> speed (for the attribute lookup) and find that all the prefixed references
> make their code look more Javaesque that Pythonesque.
> Over years of looking at tons of Python code, I've seen several variants of
> enums.  In *every* case, they were just a toy recipe and were not be used
> in anything other than demo code.

Did you also see lots of examples of people creating their own set
types? Until something is part of the language or library people will
toy with their own version but probably won't commit to it. But once
something is standardised it gets used---if it is general purpose. For
example, I use sets all the time now, but they are a relatively new
feature in Python, so before I often had dicts with None values.

[snipped examples]

> There are already so many reasonable ways to do this or avoid doing it,
> that it would be silly to add an Enum factory.

I thought that one of Python's strengths was supposed to be that in
general there is just one best way to do things.

> IMO, Enum() is in the category of recipes that are like variants of
> flatten() or Sudoku solvers; they are fun to write but no one really needs
> them.

None of the examples you gave provides any level of const-ness. Yet
namedtuple's and tuples do.

And an enum factory function for collections could be as simple as:

def enum(field_names, values=None):
    e = collections.namedtuple("_enum", field_names)
    if values is None:
        values = range(len(field_names.split()))
    return e(*values)

(Although this doesn't account for pickling.)

>>> Vehicle = enum("car van bus truck")
>>> Vehicle.car, Vehicle.van, Vehicle.bus, Vehicle.truck
(0, 1, 2, 3)
>>> Limit = enum("minimum maximum default", (-50, 50, 10))
>>> Limit.default

Mark Summerfield, Qtrac Ltd., www.qtrac.eu

More information about the Python-ideas mailing list