[issue33419] Add functools.partialclass

Nick Coghlan report at bugs.python.org
Sat May 5 11:08:08 EDT 2018


Nick Coghlan <ncoghlan at gmail.com> added the comment:

Note that Neil did start with a python-ideas discussion, and was directed over here, since the idea seemed simple enough, and worth pursuing.

As Serhiy notes though, there are many more subtleties to be addressed here than I first thought.

That said, as long as __init__, __new__ and __slots__ are handled appropriately in the partial subclass, I think custom metaclasses should largely take care of themselves, so it would be better to avoid the compatibility implications of injecting an implicit metaclass.

The slots case should be adequately handled by doing:

    if hasattr(cls, "__slots__"):
        __slots__ = ()

The __new__ case may have some quirks due to the fact it's technically implemented as an implicitly static method, but I *think* that can be covered by defining it as:

    if cls.__new__ is not object.__new__:
        __new__ = partialmethod(cls.__new__, *args, **kwds)

and relying on the native class machinery to include the same kind of fixup that it applies for any other __new__ method implementation.

__init__ will need a similar "has it been overridden?" check to the one in __new__ (comparing the unbound methods via "cls.__init__ is not object.__init__").


Some of the other issues that Serhiy mentions are real problems with the approach (like pickle compatibility, alternate constructor support, etc), but I think those can simply be noted in the documentation, with the following double-subclassing recipe noted as a suggested way of handling them:

    class MySubclass(partialclass(BaseClass, *args, **kwds)):
        ...
        # MySubclass supports pickle as it's reachable by name
        # Custom constructors can be overloaded as needed here

(Note: if you're not seeing https://github.com/python/cpython/blob/master/Doc/whatsnew/3.8.rst locally, check that you're accidentally working on the 3.7 branch, instead of the master branch)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33419>
_______________________________________


More information about the Python-bugs-list mailing list