PEP 354: Enumerations in Python

Raymond Hettinger python at rcn.com
Wed Mar 1 13:03:49 EST 2006


[Ben Finney]
> It is possible to simply define a sequence of values of some other
> basic type, such as ``int`` or ``str``, to represent discrete
> arbitrary values.  However, an enumeration ensures that such values
> are distinct from any others, and that operations without meaning
> ("Wednesday times two") are not defined for these values.

It would be useful for the PEP to add a section that discussed the pros
and cons of this approach (preferably with examples).

For instance, having values distinct from one another is only useful in
the absence of namespace qualifiers (such as Weekdays.fri).

Also, it would be useful to contrast this approach with that used for
Booleans which were implemented as an int subclass.  There, the
interoperability with other numbers turned out to be useful on
occasion:

   Q = lambda predicate, iterable: sum(predicate(val) for val in
iterable)

Likewise, the PEP's approach precludes a broad class of use cases such
as:

   Weekday.fri - Weekday.wed == 2

(where Weekday.fri > Weekday.wed implies that the difference has a
positive value).

If enumerations were implemented as an int subclass, they could serve
as a base class for booleans and enter the language in a unified way.
Likewise, they could be more readily applicable in use cases like
calendar.py which relies on math ops being defined for the days of the
week.

I would like to see the PEP develop these arguments more fully so that
the correct approach will be self evident based on the merits.


Raymond




More information about the Python-list mailing list