[Python-ideas] Enums

Nick Coghlan ncoghlan at gmail.com
Thu Jul 28 00:24:09 CEST 2011


On Tue, Jul 26, 2011 at 5:18 AM, Barry Warsaw <barry at python.org> wrote:
> Most enums (at least IME) are discrete objects that don't have a natural
> ordering.

For compatibility reasons, though, I believe it is worth following the
precedent set by bool: if integer constants are to be replaced by
named values, the replacement needs to support everything the previous
value did. The easiest way to achieve that is by inheriting directly
from the previous value's type.

I'm getting deja vu as I formulate this next bit, so I suspect I've
said similar things in the past...

1. I find the "enum" concept too limiting. NamedValue (as a mixin
class) is a better building block since it separates the naming aspect
from the "group of values" aspect implied by enum. It would be nice,
for example, if we could do things like "tau = NamedFloat('tau',
2*math.pi)" where NamedFloat is essentially just "class
NamedFloat(NamedValue, float): pass" (this could, of course, be hidden
behind a factory function that used type(value) and a cache to
dynamically create appropriate subclasses)

2. All the stdlib use cases have a relevant namespace already (the
module level one). They are better served by a namedtuple style
solution that adds naming behaviour at the object level without trying
to organise groups of named constants in any particular fashion.

3. The named value approach can improve the ease of debugging *any*
significant data structure, not just constants.

4. If named values are available as a building block, they can be used
by any enum implementation. In and of themselves they wouldn't inherit
from any particular type, so enum implementations could decide which
types to support and how comparisons and other operations should
behave.

As Raymond says, clearly none of this is *necessary*. However, the
usefulness of objects that know their official name has proven itself
extensively in the form of classes and functions, and
collections.namedtuple is a recent addition that has proven similarly
beneficial for improving the maintainability of tuples by providing
additional static metadata. Extending that kind of benefit to
arbitrary instances has clear utility without significantly impacting
compatibility (since we would be substituting instances of a class
with instances of subclasses that only modify display related
behaviour).

But the grouping behaviour? I really don't see a lot of value in that
- just boilerplate. We don't write bool.True and bool.False, we write
True and False.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list