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

Steven D'Aprano steve at pearwood.info
Fri Apr 26 14:32:53 CEST 2013


On 26/04/13 18:00, Greg Ewing wrote:

> However, there's a worse problem with defining enum
> inheritance that way. The subtype relation for extensible
> enums works the opposite way to that of classes.
>
> To see this, imagine a function expecting something
> of type Colors. It knows what to do with red, green and
> blue, but not anything else. So you *can't* pass it
> something of type MoreColors, because not all values
> of type MoreColors are of type Colors.
>
> On the other hand, you *can* pass a value of type Colors
> to something expecting MoreColors, because every value of
> Colors is also in MoreColors.
>
> Moreover, suppose we have another type:
>
>     class YetMoreColors(Colors):
>        orange = 4
>        purple = 5
>        pink = 6
>
> Now suppose a function expecting Colors gets an enum
> with the integer value 4. How should it be interpreted?
> Is it cyan or orange? What about if you write it to a
> database column and read it back?

There are many places where Python demands an actual int, not a subclass. See the recent thread "Semantics of __int__, index". There's no reason why a function that expects a Color *must* accept subclasses as well. If it can, great. If it can't, document it and move on.

It's not Color's responsibility to know everything about every subclass. Invert your thinking: the subclasses are in charge, not Color. Color can't be expected to give a value to 4. Only the subclass that defines it can. This is only a problem if you believe that subclassing == taxonomy hierarchy. It isn't.

http://pyvideo.org/video/879/the-art-of-subclassing




-- 
Steven


More information about the Python-Dev mailing list