[Python-Dev] PEP 435 -- Adding an Enum type to the Python standard library

Eli Bendersky eliben at gmail.com
Fri Apr 12 23:06:55 CEST 2013


On Fri, Apr 12, 2013 at 1:52 PM, R. David Murray <rdmurray at bitdance.com>wrote:

> On Fri, 12 Apr 2013 15:33:02 -0400, Barry Warsaw <barry at python.org> wrote:
> > On Apr 12, 2013, at 11:21 AM, Russell E. Owen wrote:
> >
> > >I, too, would strongly prefer to see ordering within an enum. I use
> > >home-made enums heavily in my code and find ordering comparisons useful
> > >there.
> >
> > This was all hashed out in gory detail on python-ideas.  I feel strongly
> that
> > base EnumValues should be unordered, especially because the underlying
> values
> > can be of any type.  What would you expect to happen in this case:
> >
> >     class X(Enum):
> >         a = 1
> >         b = 'hi'
> >
> >     if X.a < myvalue < X.b:
> >         # whaa?
> >
> > I think for most use cases, IntEnums will fit the bill for those who want
> > ordered comparisons, and it's also easy to subclass EnumValues to
> specialize
> > the behavior (in fact, this is how IntEnums are implemented).
> >
> > So if you really want ordered-comparisons-with-untyped-enum-values, you
> can
> > have them. :)
>
> You are right, the problem of comparison of disparate types makes ordering
> a non-starter.  But by the same token that means you are going to have to
> be consistent and give up on having a sorted iteration and a stable repr:
>
> >>> import enum
> >>> class Foo(enum.Enum):
> ...    aa = 1
> ...    bb = 2
> ...    cc = 'hi'
> >>> Foo
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "./enum.py", line 103, in __repr__
>     for k in sorted(cls._enums)))
> TypeError: unorderable types: str() < int()
>

I actually think that having values with different types within a single
Enum is conceptually wrong and should be disallowed at creation time. With
enums, you either care or don't care about their actual value. If you don't
care (the most common use case of an enum, IMHO), then no problem here. If
you do care, then it's probably for very specific reasons most of which are
solved by IntEnum. I can't imagine why someone would need differently typed
values in a single enum - this just seems like a completely inappropriate
use of an enum to me.

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130412/2996cfef/attachment.html>


More information about the Python-Dev mailing list