[Python-ideas] PEP for enum library type?
Markus Unterwaditzer
markus at unterwaditzer.net
Tue Feb 12 23:50:01 CET 2013
Guido van Rossum <guido at python.org> wrote:
>I'm torn. I like the clean look of Tim's:
>
>class Flag(Enum):
> RED, WHITE, BLUE
>
>However, I don't like the magic needed for its implementation -- and
>anybody who thinks they know Python pretty well and thinks about this
>syntax for more than two seconds has to wonder how on earth it's done
>(and the answer is pretty horrible). It is also pretty brittle to
>depend on the lookup order -- and I suspect it will be prone to
>masking other bugs (any typo in a name used in class-level code will
>essentially generate a bogus new enum value).
>
>OTOH I don't like having the string quotes of Antoine's
>counter-proposal:
>
>class Flag(Enum):
> fields = ('RED', 'WHITE', 'BLUE')
>
>Whenever I see quoted names that are also used unquoted, I cringe a
>little (and this includes calls to hasattr() or getattr() with a
>string literal for the name).
>
>The compromise that I would personally lean towards is more like this:
>
>class Flag(Enum):
> RED, WHITE, BLUE = <something>
>
>Even if the <something> requires you to know how many values you are
>defining, like range(3). If we have to have a somewhat more verbose
>syntax that doesn't bother me too much.
>
>FWIW I do like being able to define enums that are ints and strings
>(but not mixed); masks/flags I see more as a special case of ints (if
>you use this you are likely trying to match some API defined in C or
>C++). I also agree that it must be possible to customize the enum
>class and the behavior of the values by defining methods on the class.
>
>--
>--Guido van Rossum (python.org/~guido)
>_______________________________________________
>Python-ideas mailing list
>Python-ideas at python.org
>http://mail.python.org/mailman/listinfo/python-ideas
Forgive my naiveness, but why do we need a new type for enums? Wouldn't a new builtin function that returns a dict suffice? Something like:
def enum(*keys):
return dict((k, i) for i, k in enumerate(keys))
loglevels = enum('debug', 'warning', 'error')
-- Markus
More information about the Python-ideas
mailing list