PEP 354: Enumerations in Python

Paul Rubin http
Mon Feb 27 07:04:54 EST 2006


Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> All of the machinery of the enum class created by Ben Finney is just to
> make sure that red, green and blue behave correctly, without extraneous
> string-like or number-like methods. Of course Ben could modify his code so
> that enum() returned an object. 

>From the PEP:

    >>> Weekdays = enum('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')
    ... 
    The values are bound to attributes of the new enumeration object::
    >>> today = Weekdays.mon

Looks to me like he already has enum returning an object and he
describes it as an "enumeration object".  The values are attributes on
the object.  An empty enum simply doesn't have any of those attributes.

> But to my mind, that would be like creating an empty integer. Not
> zero -- zero is a perfectly good integer.  An empty integer, one
> with no bits. Yes, you could create a wrapper class that did
> that. But why would you want to, and even if you did, in what sense
> is the result still an integer?

It's more like a set than an integer.  You can't iterate through an
integer, but according to the PEP, you can iterate through enums.

> Then you would be happy with empty longints that are distinct from zero?
> An empty enum() is like a bitless integer. 

No, I'd say enums are like types.  The integer 0 is different from 0.0
which is different from 0+0j and your program can tell them apart.
Similarly you can make e1, e2, and e3 be distinct empty enums.

> As far as I know, neither Pascal nor C allow empty enums. And even if they
> did, what and how would you use them for?

I don't use Pascal.  C formerly didn't allow zero-length arrays (I
don't know about now) and that was a design error; a GCC extension
fixes it.  Python doesn't make that error: it supports zero-length
arrays (empty lists).  If Python fixes C's error about empty arrays it
can also fix C's error about empty enums.

Anyway, Ben's enums already differ from C and Pascal enums in two ways:

1) they are first-class objects, not syntatic sugar
2) You can iterate through them.

That's enough to say their best semantics are probably different from
C's or Pascal's.

> Think about the Python usage:
> 
> >>> fruit = Enum('apple', 'banana', 'orange')
> >>> snack = fruit[2]

The PEP doesn't have Python enums working like that.  Have you
actually read it?



More information about the Python-list mailing list