[Python-Dev] Enum: subclassing?

Antoine Pitrou solipsis at pitrou.net
Wed May 1 20:44:39 CEST 2013


On Wed, 01 May 2013 10:21:30 -0700
Ethan Furman <ethan at stoneleaf.us> wrote:
> We may not want to /completely/ disallow subclassing.  Consider:
> 
> --> class StrEnum(str, Enum):
> ...    '''string enums for Business Basic variable names'''
> ...
> --> class Vendors(StrEnum):
> EnumError: subclassing not allowed

I don't see the point of disallowing subclassing. It sounds like
a pointless restriction.

However, perhaps the constructor should forbid the returning of a base
type, e.g.:

class Season(Enum):
    spring = 1

class MySeason(Season):
    """I look nicer than Season"""

MySeason('spring')
...
ValueError: Season.spring is not a MySeason instance

(what this means is perhaps the subclassing of non-empty enum classes
should be forbidden)

Regards

Antoine.


> 
> 
> My point is that IntEnum, StrEnum, ListEnum, FloatEnum are all "subclasses" of Enum.  To then have a subclass of
> that, such as Season(StrEnum), is subclassing a subclass.
> 
> Now, if we do want to completely disallow it, we can ditch IntEnum and force the user to always specify the mixin
> type:
> 
> --> class Season(str, Enum):
>           .
>           .
>           .
> 
> --> class Names(str, Enum):
>           .
>           .
>           .
> 
> But that's not very user friendly... although it's not too bad, either.
> 
> One consequence of the way it is now (IntEnum, StrEnum, etc., are allowed) is that one can put methods and other 
> non-Enum item in a base class and then inherit from that for actual implemented Enum classes.
> 
> --> class StrEnum(str, Enum):
> ...     def describe(self):
> ...         print("Hi!  I'm a %s widget!" % self.value)
> ...
> 
> --> class Season(StrEnum):
> ...     spring = 'green'
> ...     summer = 'brown'
> ...     autumn = 'red'
> ...     winter = 'white'
> ...
> 
> --> class Planet(StrEnum):
> ...     mars = 'red'
> ...     earth = 'blue'
> ...
> 
> --> Season.summer.descripbe()
> Hi!  I'm a brown widget!
> 
> --> Planet.earth.describe()
> Hi!  I'm a blue widget!
> 
> --
> ~Ethan~





More information about the Python-Dev mailing list