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

Barry Warsaw barry at python.org
Fri Apr 12 21:26:57 CEST 2013


On Apr 12, 2013, at 09:43 AM, Guido van Rossum wrote:

>I do wonder about this passage in the PEP:
>
>> Let's say you wanted to encode an enumeration value in a database.  You
>> might want to get the enumeration class object from an enumeration value::
>>
>>     >>> cls = Colors.red.enum
>>     >>> print(cls.__name__)
>>     Colors
>
>I don't understand what this has to do with storing enums in a
>database.

Not much, really.  It's just hold over text from the original motivation for
exposing the enum class as an attribute on the values.  In Mailman, I store
these values in my database and they get reconstituted correctly by the ORM
layer.  Anyway, in this particular case, I think the motivation is unnecessary
for describing the API, so I'll remove that from the PEP.

>But it reminded me that for the purpose of storing enums in a database, it
>would be nice to have two examples: one that stores the names and looks them
>up (do you really have to use getattr() for that?), and one that stores the
>values and looks them up (how do you do that at all?).

It's going to be dependent on how you store and retrieve enum values.

As an example, in my database layer I store the enum values in an integer
column, with the ORM layer knowing which Enum subclass to use.  So all I need
to do to store the value is ``int(enum_value)`` and to get back the original
enum value, I just do ``self._enum[int_value]`` where self._enum is the Enum
subclass.  To me, that's probably the most common way of doing it.

If you store by name though, yes, you'd have to use
``getattr(self._enum, name)``.  At one point Enums also supported getitem
syntax for lookup by name, but consider this case:

class Fruit(Enum):
    apple = 'red'
    banana = 'yellow'
    tangerine = 'orange'
    orange = 'reddish yellow'

What should Fruit['orange'] return?  In private email Nick pointed out that
using getattr() for lookup by name works fine, and getitem for look up by
value has been in the API since the beginning, so now Fruit['orange'] is
documented to return Fruit.tangerine, i.e. lookup by value only.  (Actually,
in flufl.enum, lookup-by-name is still there but deprecated.  We can just drop
it for Python 3.4).

>Should the metaclass-based API used to create IntEnum be documented,
>so strongly motivated people can write their own crazy variants?

I think you recommended against that in python-ideas :).

-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130412/2d102644/attachment-0001.pgp>


More information about the Python-Dev mailing list