PEP 354: Enumerations in Python

Ben Finney bignose+hates-spam at benfinney.id.au
Mon Feb 27 20:16:17 EST 2006


"Giovanni Bajo" <noway at sorry.com> writes:
> Ben Finney wrote:
>> Values within an enumeration cannot be meaningfully compared except
>> with values from the same enumeration.  The comparison operation
>> functions return ``NotImplemented`` [#CMP-NOTIMPLEMENTED]_ when a
>> value from an enumeration is compared against any value not from the
>> same enumeration or of a different type::
>> [...]
>> This allows the operation to succeed, evaluating to a boolean value::
>
> Given that this is going to change in Python 3.0 for builtin types,
> I'm not sure there's much reason to keep it this way.

What is it that will change? Can you point to something we should read
about this?

> I'd rather a comparison operation between different enum types to
> raise an exception. This would be a very compelling feature to use
> enum (and in fact, the implementation I chose in Cookbook for my
> programs have this feature).

A previous implementation raised exceptions from failed comparisons.
Here is the discussion that convinced me that was not the right thing
to do::

    <URL:http://groups.google.com/group/comp.lang.python/browse_thread/thread/140de1765bbb8d2d/>

>> Coercing a value from an enumeration to a ``str`` results in the
>> string that was specified for that value when constructing the
>> enumeration::
>>
>>     >>> gym_night = Weekdays.wed
>>     >>> str(gym_night)
>>     'wed'
>
> What's the repr of an enumeration value?

Hmm, the PEP doesn't specify. I was leaving it up to the
implementation.

> OTOH, it should be something like "Weekdays.wed", so that
> eval(repr()) holds true. Also, it'd be very useful in debug dumps,
> tracebacks and whatnot.

An enumeration value object knows the enumeration object that created
it, but that enumeration doesn't know its own name; objects don't know
their own name, since they could have many, or none.

Even if an enumeration value were to know the name of the enumeration
that created it, you still have this problem::

    >>> Colours = enum('red', 'green', 'blue')
    >>> repr(Colours.green)
    Colours.green
    >>> Lamps = Colours
    >>> repr(Lamps.red)
    Colours.red

Is this desirable behaviour? I don't think so.

-- 
 \        "I went to the hardware store and bought some used paint. It |
  `\                   was in the shape of a house."  -- Steven Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list