[Python-Dev] PEP487: Simpler customization of class creation

Martin Teichmann lkb.teichmann at gmail.com
Sun Jul 3 17:56:57 EDT 2016

Hi Nick,

thanks for the nice review!

> I think making __init_subclass__ implicitly a class method is still
> the right thing to do if this proposal gets accepted, we'll just want
> to see if we can do something to tidy up that aspect of the
> documentation at the same time.

I could write some documentation, I just don't know where to put it.
I personally have no strong feelings whether __init_subclass__ should
be implicitly a @classmethod or not - but as the general consensus here
seemed to hint making it implicit is better, this is how I wrote it.

>> While implementing PEP 487 I realized that there is and oddity in the
>> type base class: type.__init__ forbids to use keyword arguments, even
>> for the usual three arguments it has (name, base and dict), while
>> type.__new__ allows for keyword arguments. As I plan to forward any
>> keyword arguments to the new __init_subclass__, I stumbled over that.
>> As I write in the PEP, I think it would be a good idea to forbid using
>> keyword arguments for type.__new__ as well. But if people think this
>> would be to big of a change, it would be possible to do it
>> differently.
> [some discussion cut out]
> I think the PEP could be accepted without cleaning this up, though -
> it would just mean __init_subclass__ would see the "name", "bases" and
> "dict" keys when someone attempted to use keyword arguments with the
> dynamic type creation APIs.

Yes, this would be possible, albeit a bit ugly. I'm not so sure whether
backwards compatibility is so important in this case. It is very
easy to change the code to the fully cleaned up version

Looking through old stuff I found http://bugs.python.org/issue23722,
which describes the following problem: at the time __init_subclass__ is
called, super() doesn't work yet for the new class. It does work for
__init_subclass__, because it is called on the base class, but not for
calls to other classmethods it does. This is a pity especially because
also the two argument form of super() cannot be used as the new
class has no name yet.

The problem is solvable though. The initializations necessary for
super() to work properly simply should be moved before the call
to __init_subclass__. I implemented that by putting a new attribute
into the class's namespace to keep the cell which will later be used
by super(). This new attribute would be remove by type.__new__
again, but transiently it would be visible. This technique has already
been used for __qualname__.

The issue contains a patch that fixes that behavior, and back in the
day you proposed I add the problem to the PEP. Should I?



More information about the Python-Dev mailing list