[Python-ideas] PEP for enum library type?

Tim Delaney timothy.c.delaney at gmail.com
Tue Feb 12 21:13:21 CET 2013


Sorry to anyone who gets this twice - sent it from my work address which is
not subscribed to Python-Ideas.

On 13 February 2013 06:13, Guido van Rossum <guido at python.org> wrote:

> > As far as typos go, I don't think that's a new problem (it certainly
> isn't
> > for me, anyway ;) and my best defense is plenty of tests.
>
> So with Tim's implementation, what happens here:
>
> class Color(Enum):
>   RED, GREEN, BLUE
>   if sys.platform == 'win32':
>     MAGENTA
>
> and you happen to have no "import sys" in your module? The sys lookup
> will succeed, create a new enum, and then you will get an error
> something like this:
>
> AttributeError: 'Enum' object has no attribute 'platform'


Well, that particular case would work (you'd get a NameError: sys) due to
having done an attribute lookup on sys, but the following:

class Color(Enum):
    RED, GREEN, BLUE
    if platfor == 'win32':
        MAGENTA

would create an enum value 'platfor'.

Personally, I don't think it's possible to have an enum with a simple
interface and powerful semantics with just python code without it being
fragile. I think I've got it fairly close, but there is horrible magic in
there (multiple kinds) and there are definitely still edge cases. Any
complete enum implementation is going to need some special handling by the
parser I think.

I'm actually thinking that to simplify things, I need a sentinel object to
mark the end of the enum list (which allows other names after it). But that
still wouldn't handle the case above (the if statement).

BTW, for anyone who hasn't seen the magic code (largely uncommented, no
explanations yet of how it's doing it - I probably won't get to that until
the weekend) it's here: https://bitbucket.org/magao/enum

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130213/4d8d4e6f/attachment.html>


More information about the Python-ideas mailing list