[Python-Dev] PEP 435 -- Adding an Enum type to the Python standard library
greg.ewing at canterbury.ac.nz
Fri Apr 26 10:00:15 CEST 2013
Piotr Duda wrote:
> There is at least one more problem, enum inheritance, given:
> class Colors(Enum):
> red = 1
> green = 2
> blue = 3
> class MoreColors(Color):
> cyan = 4
> magenta = 5
> yellow = 6
> what type is MoreColors.red?
Given the implementation we're considering, it would
probably be Colors.
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:
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?
These considerations suggest to me that subclassing
enums should be disallowed, or at least not officially
More information about the Python-Dev