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

Raymond Hettinger python at rcn.com
Thu Jan 24 10:02:50 CET 2008

[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.  I know it's possible to invent use cases for this, but I think real world needs 
have largely been met through module and class namespaces.  If you have a lot of constants, the simple approach is to put them in 
their own module and then reference them using mod.name.  If there are a medium number, then a class namespace (like the first 
example below) may be preferable.  If there are only a few, the people seem to be happy with globals.

Something like "wheres= Enum( UP= 0, DOWN= 0, LEFT= 0, RIGHT= 0 )" is easily written as:

    class wheres:
        UP = 0; DOWN = 0; LEFT = 0; RIGHT = 0

Or equivalently:

       wheres = type('wheres', (), dict(UP= 0, DOWN= 0, LEFT= 0, RIGHT= 0 ))

Or using the module approach:

     -- wheres.py --
     UP = 0; DOWN = 0; LEFT = 0; RIGHT = 0

      --- mymod.py --
      import wheres
      prints where.UP

Or using globals approach and avoid the attribute lookup:

      UP = 0; DOWN = 0; LEFT = 0; RIGHT = 0

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

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.

not-everything-in-the-cookbook-needs-to-be-in-the-library-ly yours,


More information about the Python-ideas mailing list