[Python-Dev] PEP-435 reference implementation

Nick Coghlan ncoghlan at gmail.com
Thu May 2 00:54:10 CEST 2013


On 2 May 2013 02:46, "Guido van Rossum" <guido at python.org> wrote:
>
> On Wed, May 1, 2013 at 9:18 AM, Tres Seaver <tseaver at palladion.com> wrote:
> > I'd be glad to drop both of those in favor of subclassing:  I think the
> > emphasis on "class-ness" makes no sense, given the driving usecases for
> > adopting enums into the stdlib in the first place.   IOW, I would vote
> > that real-world usecases trump hypothetical purity.
>
> Yeah, this is the dilemma. But what *are* the real-world use cases?
> Please provide some.
>
> Here's how I would implement "extending" an enum if subclassing were
> not allowed:
>
> class Color(Enum):
>   red = 1
>   white = 2
>   blue = 3
>
> class ExtraColor(Enum):
>   orange = 4
>   yellow = 5
>   green = 6
>
> flag_colors = set(Color) | set(ExtraColor)
>
> Now I can test "c in flag_colors" to check whether c is a flag color.
> I can also loop over flag_colors. If I want the colors in definition
> order I could use a list instead:
>
> ordered_flag_colors = list(Color) + list(ExtraColor)
>
> But this would be less or more acceptable depending on whether it is a
> common or esoteric use case.

If enums had an "as_dict" method that returned an ordered dictionary, you
could do:

class MoreColors(Enum):
    locals().update(Colors.as_dict())
    orange = 4
    ...

Using a similar API to PEP 422's class initialisation hook, you could even
simplify that to:

class MoreColors(Enum,  namespace=Colors.as_dict()):
    orange = 4
    ...

Cheers,
Nick.

>
> --
> --Guido van Rossum (python.org/~guido)
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe:
http://mail.python.org/mailman/options/python-dev/ncoghlan%40gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130502/716bd3ae/attachment.html>


More information about the Python-Dev mailing list