[Python-Dev] Enum: subclassing?

Eli Bendersky eliben at gmail.com
Wed May 1 23:19:00 CEST 2013


On Wed, May 1, 2013 at 2:07 PM, Guido van Rossum <guido at python.org> wrote:

> On Wed, May 1, 2013 at 2:04 PM, Eli Bendersky <eliben at gmail.com> wrote:
> >
> >
> >
> > On Wed, May 1, 2013 at 2:00 PM, Antoine Pitrou <solipsis at pitrou.net>
> wrote:
> >>
> >> On Wed, 1 May 2013 13:57:11 -0700
> >> Eli Bendersky <eliben at gmail.com> wrote:
> >> >
> >> > I still don't understand what you mean, sorry. Like, this:
> >> >
> >> > class MyEmptyEnum(Enum):
> >> >   pass
> >> >
> >> > Why would you want to subclass MyEmptyEnum ?
> >> >
> >> > Or do you mean this:
> >> >
> >> > class IntEnum(int, Enum):
> >> >   pass
> >> >
> >> > Now I can have:
> >> >
> >> > class SocketFamily(IntEnum):
> >> >   ??
> >> >
> >> > If it's the latter, then why allow subclassing explicitly just for
> this
> >> > reason?
> >>
> >> Because I may want to share methods accross all concrete subclasses of
> >> IntEnum (or WhateverEnum).
> >
> >
> > You mean this?
> >
> > class BehaviorMixin:
> >   # bla bla
> >
> > class MyBehavingIntEnum(int, BehaviorMixin, Enum):
> >   foo = 1
> >   bar = 2
>
> It's a common pattern to do this with a base class rather than a
> mixin, though, and I think the rule "only allow subclassing empty
> enums" makes a lot of sense.
>

I see your point (and Antoine's example in the next email is good), but my
concern is that this is a TIMTOWTDI thing, since the same can be achieved
with mixins. Specifically, Antoine's example
 becomes:

class IETFStatusCode:
    @classmethod
    def from_statusline(cls, line):
        return cls(int(line.split()[0]))

class HTTPStatusCode(int, IETFStatusCode, Enum):
    NOT_FOUND = 404

class SIPStatusCode(int, IETFStatusCode, Enum):
    RINGING = 180

Same thing, while keeping the stdlib API cleaner and more minimal. Cleaner
because "no subclassing" is a simpler, more explicit, and easier to
understand rule than "no subclassing unless base class is devoid of
enumeration values". And because we can no longer say "Enum classes are
final", which is a relatively familiar and understood semantic.

That said, I don't feel strongly about this so if the above does not
convert you, I'm fine with allowing subclassing enum classes that don't
define any enums =)

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130501/33bd60d7/attachment.html>


More information about the Python-Dev mailing list