[Python-Dev] Enum: subclassing?

Eli Bendersky eliben at gmail.com
Wed May 1 22:09:53 CEST 2013


On Wed, May 1, 2013 at 11:47 AM, Georg Brandl <g.brandl at gmx.net> wrote:

> Am 01.05.2013 20:04, schrieb Eli Bendersky:
>
> > Actually, in flufl.enum, IntEnum had to define a magic __value_factory__
> > attribute, but in the current ref435 implementation this isn't needed, so
> > IntEnum is just:
> >
> > class IntEnum(int, Enum):
> >     '''
> >     Class where every instance is a subclass of int.
> >     '''
> >
> > So why don't we just drop IntEnum from the API and tell users they
> should do the
> > above explicitly, i.e.:
> >
> > class SocketFamily(int, Enum):
> >   AF_UNIX = 1
> >   AF_INET = 2
> >
> > As opposed to having an IntEnum explicitly, this just saves 2 characters
> > (comma+space), but is more explicit (zen!) and helps us avoid the
> special-casing
> > the subclass restriction implementation.
>
> Wait a moment... it might not be immediately useful for IntEnums (however,
> that's because base Enum currently defines __int__ which I find
> questionable),
> but with  current ref435 you *can* create your own enum base classes with
> your
> own methods, and derive concrete enums from that.  It also lets you have a
> base class for enums and use it in isinstance().
>
> If you forbid subclassing completely that will be impossible.
>

I'm not sure what you mean, Georg, could you clarify?
This works:

>>> from ref435 import Enum
>>> class SocketFamily(int, Enum):
...   AF_UNIX = 1
...   AF_INET = 2
...
>>> SocketFamily.AF_INET
SocketFamily.AF_INET [value=2]
>>> SocketFamily.AF_INET == 2
True
>>> type(SocketFamily.AF_INET)
<Enum 'SocketFamily'>
>>> isinstance(SocketFamily.AF_INET, SocketFamily)
True

Now, with the way things are currently implemented, class IntEnum is just
syntactic sugar for above. Guido decided against allowing any kind of
subclassing, but as an implementation need we should keep some restricted
form to implement IntEnum. But is IntEnum really needed if the above
explicit multiple-inheritance of int and Enum is possible?

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


More information about the Python-Dev mailing list