PEP487: Simpler customization of class creation
Hi list, another round for PEP 487, is there any chance it still makes it into Python 3.6? The PEP should be effectively done, I updated the examples in it, given that I implemented the PEP I could actually test the examples, so now they work. The implementation is at http://bugs.python.org/issue27366, including documentation and tests. Unfortunately nobody has reviewed the patch yet. The new version of the PEP is attached. Greetings Martin PEP: 487 Title: Simpler customisation of class creation Version: $Revision$ Last-Modified: $Date$ Author: Martin Teichmann <lkb.teichmann@gmail.com>, Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 27-Feb-2015 Python-Version: 3.6 Post-History: 27-Feb-2015, 5-Feb-2016, 24-Jun-2016, 2-Jul-2016, 13-Jul-2016 Replaces: 422 Abstract ======== Currently, customising class creation requires the use of a custom metaclass. This custom metaclass then persists for the entire lifecycle of the class, creating the potential for spurious metaclass conflicts. This PEP proposes to instead support a wide range of customisation scenarios through a new ``__init_subclass__`` hook in the class body, and a hook to initialize attributes. The new mechanism should be easier to understand and use than implementing a custom metaclass, and thus should provide a gentler introduction to the full power of Python's metaclass machinery. Background ========== Metaclasses are a powerful tool to customize class creation. They have, however, the problem that there is no automatic way to combine metaclasses. If one wants to use two metaclasses for a class, a new metaclass combining those two needs to be created, typically manually. This need often occurs as a surprise to a user: inheriting from two base classes coming from two different libraries suddenly raises the necessity to manually create a combined metaclass, where typically one is not interested in those details about the libraries at all. This becomes even worse if one library starts to make use of a metaclass which it has not done before. While the library itself continues to work perfectly, suddenly every code combining those classes with classes from another library fails. Proposal ======== While there are many possible ways to use a metaclass, the vast majority of use cases falls into just three categories: some initialization code running after class creation, the initalization of descriptors and keeping the order in which class attributes were defined. The first two categories can easily be achieved by having simple hooks into the class creation: 1. An ``__init_subclass__`` hook that initializes all subclasses of a given class. 2. upon class creation, a ``__set_owner__`` hook is called on all the attribute (descriptors) defined in the class, and The third category is the topic of another PEP 520. As an example, the first use case looks as follows::
class QuestBase: ... # this is implicitly a @classmethod ... def __init_subclass__(cls, swallow, **kwargs): ... cls.swallow = swallow ... super().__init_subclass__(**kwargs)
class Quest(QuestBase, swallow="african"): ... pass
Quest.swallow 'african'
The base class ``object`` contains an empty ``__init_subclass__`` method which serves as an endpoint for cooperative multiple inheritance. Note that this method has no keyword arguments, meaning that all methods which are more specialized have to process all keyword arguments. This general proposal is not a new idea (it was first suggested for inclusion in the language definition `more than 10 years ago`_, and a similar mechanism has long been supported by `Zope's ExtensionClass`_), but the situation has changed sufficiently in recent years that the idea is worth reconsidering for inclusion. The second part of the proposal adds an ``__set_owner__`` initializer for class attributes, especially if they are descriptors. Descriptors are defined in the body of a class, but they do not know anything about that class, they do not even know the name they are accessed with. They do get to know their owner once ``__get__`` is called, but still they do not know their name. This is unfortunate, for example they cannot put their associated value into their object's ``__dict__`` under their name, since they do not know that name. This problem has been solved many times, and is one of the most important reasons to have a metaclass in a library. While it would be easy to implement such a mechanism using the first part of the proposal, it makes sense to have one solution for this problem for everyone. To give an example of its usage, imagine a descriptor representing weak referenced values:: import weakref class WeakAttribute: def __get__(self, instance, owner): return instance.__dict__[self.name]() def __set__(self, instance, value): instance.__dict__[self.name] = weakref.ref(value) # this is the new initializer: def __set_owner__(self, owner, name): self.name = name While this example looks very trivial, it should be noted that until now such an attribute cannot be defined without the use of a metaclass. And given that such a metaclass can make life very hard, this kind of attribute does not exist yet. Initializing descriptors could simply be done in the ``__init_subclass__`` hook. But this would mean that descriptors can only be used in classes that have the proper hook, the generic version like in the example would not work generally. One could also call ``__set_owner__`` from whithin the base implementation of ``object.__init_subclass__``. But given that it is a common mistake to forget to call ``super()``, it would happen too often that suddenly descriptors are not initialized. Key Benefits ============ Easier inheritance of definition time behaviour ----------------------------------------------- Understanding Python's metaclasses requires a deep understanding of the type system and the class construction process. This is legitimately seen as challenging, due to the need to keep multiple moving parts (the code, the metaclass hint, the actual metaclass, the class object, instances of the class object) clearly distinct in your mind. Even when you know the rules, it's still easy to make a mistake if you're not being extremely careful. Understanding the proposed implicit class initialization hook only requires ordinary method inheritance, which isn't quite as daunting a task. The new hook provides a more gradual path towards understanding all of the phases involved in the class definition process. Reduced chance of metaclass conflicts ------------------------------------- One of the big issues that makes library authors reluctant to use metaclasses (even when they would be appropriate) is the risk of metaclass conflicts. These occur whenever two unrelated metaclasses are used by the desired parents of a class definition. This risk also makes it very difficult to *add* a metaclass to a class that has previously been published without one. By contrast, adding an ``__init_subclass__`` method to an existing type poses a similar level of risk to adding an ``__init__`` method: technically, there is a risk of breaking poorly implemented subclasses, but when that occurs, it is recognised as a bug in the subclass rather than the library author breaching backwards compatibility guarantees. New Ways of Using Classes ========================= Subclass registration --------------------- Especially when writing a plugin system, one likes to register new subclasses of a plugin baseclass. This can be done as follows:: class PluginBase(Object): subclasses = [] def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.subclasses.append(cls) In this example, ``PluginBase.subclasses`` will contain a plain list of all subclasses in the entire inheritance tree. One should note that this also works nicely as a mixin class. Trait descriptors ----------------- There are many designs of Python descriptors in the wild which, for example, check boundaries of values. Often those "traits" need some support of a metaclass to work. This is how this would look like with this PEP:: class Trait: def __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum def __get__(self, instance, owner): return instance.__dict__[self.key] def __set__(self, instance, value): if self.minimum < value < self.maximum: instance.__dict__[self.key] = value else: raise ValueError("value not in range") def __set_owner__(self, owner, name): self.key = name Implementation Details ====================== For those who prefer reading Python over english, the following is a Python equivalent of the C API changes proposed in this PEP, where the new ``object`` and ``type`` defined here inherit from the usual ones:: import types class type(type): def __new__(cls, *args, **kwargs): if len(args) == 1: return super().__new__(cls, args[0]) name, bases, ns = args init = ns.get('__init_subclass__') if isinstance(init, types.FunctionType): ns['__init_subclass__'] = classmethod(init) self = super().__new__(cls, name, bases, ns) for k, v in self.__dict__.items(): func = getattr(v, '__set_owner__', None) if func is not None: func(self, k) super(self, self).__init_subclass__(**kwargs) return self def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns) class object: @classmethod def __init_subclass__(cls): pass class object(object, metaclass=type): pass In this code, first the ``__set_owner__`` are called on the descriptors, and then the ``__init_subclass__``. This means that subclass initializers already see the fully initialized descriptors. This way, ``__init_subclass__`` users can fix all descriptors again if this is needed. Another option would have been to call ``__set_owner__`` in the base implementation of ``object.__init_subclass__``. This way it would be possible event to prevent ``__set_owner__`` from being called. Most of the times, however, such a prevention would be accidental, as it often happens that a call to ``super()`` is forgotten. Another small change should be noted here: in the current implementation of CPython, ``type.__init__`` explicitly forbids the use of keyword arguments, while ``type.__new__`` allows for its attributes to be shipped as keyword arguments. This is weirdly incoherent, and thus the above code forbids that. While it would be possible to retain the current behavior, it would be better if this was fixed, as it is probably not used at all: the only use case would be that at metaclass calls its ``super().__new__`` with *name*, *bases* and *dict* (yes, *dict*, not *namespace* or *ns* as mostly used with modern metaclasses) as keyword arguments. This should not be done. As a second change, the new ``type.__init__`` just ignores keyword arguments. Currently, it insists that no keyword arguments are given. This leads to a (wanted) error if one gives keyword arguments to a class declaration if the metaclass does not process them. Metaclass authors that do want to accept keyword arguments must filter them out by overriding ``__init___``. In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``. Rejected Design Options ======================= Calling the hook on the class itself ------------------------------------ Adding an ``__autodecorate__`` hook that would be called on the class itself was the proposed idea of PEP 422. Most examples work the same way or even better if the hook is called on the subclass. In general, it is much easier to explicitly call the hook on the class in which it is defined (to opt-in to such a behavior) than to opt-out, meaning that one does not want the hook to be called on the class it is defined in. This becomes most evident if the class in question is designed as a mixin: it is very unlikely that the code of the mixin is to be executed for the mixin class itself, as it is not supposed to be a complete class on its own. The original proposal also made major changes in the class initialization process, rendering it impossible to back-port the proposal to older Python versions. More importantly, having a pure Python implementation allows us to take two preliminary steps before before we actually change the interpreter, giving us the chance to iron out all possible wrinkles in the API. Other variants of calling the hook ---------------------------------- Other names for the hook were presented, namely ``__decorate__`` or ``__autodecorate__``. This proposal opts for ``__init_subclass__`` as it is very close to the ``__init__`` method, just for the subclass, while it is not very close to decorators, as it does not return the class. Requiring an explicit decorator on ``__init_subclass__`` -------------------------------------------------------- One could require the explicit use of ``@classmethod`` on the ``__init_subclass__`` decorator. It was made implicit since there's no sensible interpretation for leaving it out, and that case would need to be detected anyway in order to give a useful error message. This decision was reinforced after noticing that the user experience of defining ``__prepare__`` and forgetting the ``@classmethod`` method decorator is singularly incomprehensible (particularly since PEP 3115 documents it as an ordinary method, and the current documentation doesn't explicitly say anything one way or the other). A more ``__new__``-like hook ---------------------------- In PEP 422 the hook worked more like the ``__new__`` method than the ``__init__`` method, meaning that it returned a class instead of modifying one. This allows a bit more flexibility, but at the cost of much harder implementation and undesired side effects. Adding a class attribute with the attribute order ------------------------------------------------- This got its own PEP 520. History ======= This used to be a competing proposal to PEP 422 by Nick Coghlan and Daniel Urban. PEP 422 intended to achieve the same goals as this PEP, but with a different way of implementation. In the meantime, PEP 422 has been withdrawn favouring this approach. References ========== .. _more than 10 years ago: http://mail.python.org/pipermail/python-dev/2001-November/018651.html .. _Zope's ExtensionClass: http://docs.zope.org/zope_secrets/extensionclass.html Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End:
On 14 July 2016 at 00:15, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi list,
another round for PEP 487, is there any chance it still makes it into Python 3.6?
The PEP should be effectively done, I updated the examples in it, given that I implemented the PEP I could actually test the examples, so now they work.
The implementation is at http://bugs.python.org/issue27366, including documentation and tests. Unfortunately nobody has reviewed the patch yet.
The new version of the PEP is attached.
+1 from me for this version - between them, this and PEP 520 address everything I hoped to achieve with PEP 422, and a bit more besides. There's no BDFL delegation in place for this one though, so it's really Guido's +1 that you need :) Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
I'm reviewing this now. Martin, can you please submit the new version of your PEP as a Pull Request to the new peps repo on GitHub? https://github.com/python/peps --Guido On Wed, Jul 13, 2016 at 7:45 AM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 14 July 2016 at 00:15, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi list,
another round for PEP 487, is there any chance it still makes it into Python 3.6?
The PEP should be effectively done, I updated the examples in it, given that I implemented the PEP I could actually test the examples, so now they work.
The implementation is at http://bugs.python.org/issue27366, including documentation and tests. Unfortunately nobody has reviewed the patch yet.
The new version of the PEP is attached.
+1 from me for this version - between them, this and PEP 520 address everything I hoped to achieve with PEP 422, and a bit more besides.
There's no BDFL delegation in place for this one though, so it's really Guido's +1 that you need :)
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
FWIW I copied the version you posted into the peps repo already, since it provides a significant update to the last version there. On Wed, Jul 13, 2016 at 2:02 PM, Guido van Rossum <guido@python.org> wrote:
I'm reviewing this now.
Martin, can you please submit the new version of your PEP as a Pull Request to the new peps repo on GitHub? https://github.com/python/peps
--Guido
On Wed, Jul 13, 2016 at 7:45 AM, Nick Coghlan <ncoghlan@gmail.com> wrote:
On 14 July 2016 at 00:15, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi list,
another round for PEP 487, is there any chance it still makes it into Python 3.6?
The PEP should be effectively done, I updated the examples in it, given that I implemented the PEP I could actually test the examples, so now they work.
The implementation is at http://bugs.python.org/issue27366, including documentation and tests. Unfortunately nobody has reviewed the patch yet.
The new version of the PEP is attached.
+1 from me for this version - between them, this and PEP 520 address everything I hoped to achieve with PEP 422, and a bit more besides.
There's no BDFL delegation in place for this one though, so it's really Guido's +1 that you need :)
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
-- --Guido van Rossum (python.org/~guido)
On Wed, Jul 13, 2016 at 7:15 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi list,
another round for PEP 487, is there any chance it still makes it into Python 3.6?
Sure, feature freeze isn't until September (https://www.python.org/dev/peps/pep-0494/).
The PEP should be effectively done, I updated the examples in it, given that I implemented the PEP I could actually test the examples, so now they work.
I am +1 on the idea of the PEP; below I am just asking for some clarifications and pointing out a typo or two. Please submit the next version to the github peps project as a PR! Re-review should be much quicker then.
The implementation is at http://bugs.python.org/issue27366, including documentation and tests. Unfortunately nobody has reviewed the patch yet.
Sorry, I don't have time for that part, but I'm sure once the PEP is approved the review will follow.
The new version of the PEP is attached.
Greetings
Martin
PEP: 487 Title: Simpler customisation of class creation Version: $Revision$ Last-Modified: $Date$ Author: Martin Teichmann <lkb.teichmann@gmail.com>, Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 27-Feb-2015 Python-Version: 3.6 Post-History: 27-Feb-2015, 5-Feb-2016, 24-Jun-2016, 2-Jul-2016, 13-Jul-2016 Replaces: 422
Abstract ========
Currently, customising class creation requires the use of a custom metaclass. This custom metaclass then persists for the entire lifecycle of the class, creating the potential for spurious metaclass conflicts.
This PEP proposes to instead support a wide range of customisation scenarios through a new ``__init_subclass__`` hook in the class body, and a hook to initialize attributes.
The new mechanism should be easier to understand and use than implementing a custom metaclass, and thus should provide a gentler introduction to the full power of Python's metaclass machinery.
Background ==========
Metaclasses are a powerful tool to customize class creation. They have, however, the problem that there is no automatic way to combine metaclasses. If one wants to use two metaclasses for a class, a new metaclass combining those two needs to be created, typically manually.
This need often occurs as a surprise to a user: inheriting from two base classes coming from two different libraries suddenly raises the necessity to manually create a combined metaclass, where typically one is not interested in those details about the libraries at all. This becomes even worse if one library starts to make use of a metaclass which it has not done before. While the library itself continues to work perfectly, suddenly every code combining those classes with classes from another library fails.
Proposal ========
While there are many possible ways to use a metaclass, the vast majority of use cases falls into just three categories: some initialization code running after class creation, the initalization of descriptors and
initialization
keeping the order in which class attributes were defined.
The first two categories can easily be achieved by having simple hooks into the class creation:
1. An ``__init_subclass__`` hook that initializes all subclasses of a given class. 2. upon class creation, a ``__set_owner__`` hook is called on all the attribute (descriptors) defined in the class, and
The third category is the topic of another PEP 520.
PEP, PEP 520.
As an example, the first use case looks as follows::
class QuestBase: ... # this is implicitly a @classmethod
maybe add "(see below for motivation)" ?
... def __init_subclass__(cls, swallow, **kwargs): ... cls.swallow = swallow ... super().__init_subclass__(**kwargs)
class Quest(QuestBase, swallow="african"): ... pass
Quest.swallow 'african'
The base class ``object`` contains an empty ``__init_subclass__`` method which serves as an endpoint for cooperative multiple inheritance. Note that this method has no keyword arguments, meaning that all methods which are more specialized have to process all keyword arguments.
This general proposal is not a new idea (it was first suggested for inclusion in the language definition `more than 10 years ago`_, and a similar mechanism has long been supported by `Zope's ExtensionClass`_), but the situation has changed sufficiently in recent years that the idea is worth reconsidering for inclusion.
The second part of the proposal adds an ``__set_owner__`` initializer for class attributes, especially if they are descriptors. Descriptors are defined in the body of a class, but they do not know anything about that class, they do not even know the name they are accessed with. They do get to know their owner once ``__get__`` is called, but still they do not know their name. This is unfortunate, for example they cannot put their associated value into their object's ``__dict__`` under their name, since they do not know that name. This problem has been solved many times, and is one of the most important reasons to have a metaclass in a library. While it would be easy to implement such a mechanism using the first part of the proposal, it makes sense to have one solution for this problem for everyone.
To give an example of its usage, imagine a descriptor representing weak referenced values::
import weakref
class WeakAttribute: def __get__(self, instance, owner): return instance.__dict__[self.name]()
def __set__(self, instance, value): instance.__dict__[self.name] = weakref.ref(value)
# this is the new initializer: def __set_owner__(self, owner, name): self.name = name
This example is missing something -- an example of how the WeakAttribute class would be *used*. I suppose something like # We wish we could write class C: foo = WeakAttribute() x = C() x.foo = ... print(x.foo)
While this example looks very trivial, it should be noted that until now such an attribute cannot be defined without the use of a metaclass. And given that such a metaclass can make life very hard, this kind of attribute does not exist yet.
Initializing descriptors could simply be done in the ``__init_subclass__`` hook. But this would mean that descriptors can only be used in classes that have the proper hook, the generic version like in the example would not work generally. One could also call ``__set_owner__`` from whithin the base implementation of ``object.__init_subclass__``. But given that it is a common mistake to forget to call ``super()``, it would happen too often that suddenly descriptors are not initialized.
Key Benefits ============
Easier inheritance of definition time behaviour -----------------------------------------------
Understanding Python's metaclasses requires a deep understanding of the type system and the class construction process. This is legitimately seen as challenging, due to the need to keep multiple moving parts (the code, the metaclass hint, the actual metaclass, the class object, instances of the class object) clearly distinct in your mind. Even when you know the rules, it's still easy to make a mistake if you're not being extremely careful.
Understanding the proposed implicit class initialization hook only requires ordinary method inheritance, which isn't quite as daunting a task. The new hook provides a more gradual path towards understanding all of the phases involved in the class definition process.
Reduced chance of metaclass conflicts -------------------------------------
One of the big issues that makes library authors reluctant to use metaclasses (even when they would be appropriate) is the risk of metaclass conflicts. These occur whenever two unrelated metaclasses are used by the desired parents of a class definition. This risk also makes it very difficult to *add* a metaclass to a class that has previously been published without one.
By contrast, adding an ``__init_subclass__`` method to an existing type poses a similar level of risk to adding an ``__init__`` method: technically, there is a risk of breaking poorly implemented subclasses, but when that occurs, it is recognised as a bug in the subclass rather than the library author breaching backwards compatibility guarantees.
New Ways of Using Classes =========================
Subclass registration ---------------------
Especially when writing a plugin system, one likes to register new subclasses of a plugin baseclass. This can be done as follows::
class PluginBase(Object):
What is "Object"? I presume just a typo for "object"?
subclasses = []
def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.subclasses.append(cls)
In this example, ``PluginBase.subclasses`` will contain a plain list of all subclasses in the entire inheritance tree. One should note that this also works nicely as a mixin class.
Trait descriptors -----------------
There are many designs of Python descriptors in the wild which, for example, check boundaries of values. Often those "traits" need some support of a metaclass to work. This is how this would look like with this PEP::
class Trait: def __init__(self, minimum, maximum): self.minimum = minimum self.maximum = maximum
def __get__(self, instance, owner): return instance.__dict__[self.key]
def __set__(self, instance, value): if self.minimum < value < self.maximum: instance.__dict__[self.key] = value else: raise ValueError("value not in range")
def __set_owner__(self, owner, name):
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
self.key = name
Implementation Details ======================
For those who prefer reading Python over english, the following is a Python equivalent of the C API changes proposed in this PEP, where the new ``object`` and ``type`` defined here inherit from the usual ones::
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
import types
class type(type): def __new__(cls, *args, **kwargs): if len(args) == 1: return super().__new__(cls, args[0]) name, bases, ns = args init = ns.get('__init_subclass__') if isinstance(init, types.FunctionType): ns['__init_subclass__'] = classmethod(init) self = super().__new__(cls, name, bases, ns) for k, v in self.__dict__.items(): func = getattr(v, '__set_owner__', None) if func is not None: func(self, k) super(self, self).__init_subclass__(**kwargs) return self
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
In this code, first the ``__set_owner__`` are called on the descriptors, and then the ``__init_subclass__``. This means that subclass initializers already see the fully initialized descriptors. This way, ``__init_subclass__`` users can fix all descriptors again if this is needed.
Another option would have been to call ``__set_owner__`` in the base implementation of ``object.__init_subclass__``. This way it would be possible event to prevent ``__set_owner__`` from being called. Most of the times,
event to prevent???
however, such a prevention would be accidental, as it often happens that a call to ``super()`` is forgotten.
Another small change should be noted here: in the current implementation of CPython, ``type.__init__`` explicitly forbids the use of keyword arguments, while ``type.__new__`` allows for its attributes to be shipped as keyword arguments. This is weirdly incoherent, and thus the above code forbids that. While it would be possible to retain the current behavior, it would be better if this was fixed, as it is probably not used at all: the only use case would be that at metaclass calls its ``super().__new__`` with *name*, *bases* and *dict* (yes, *dict*, not *namespace* or *ns* as mostly used with modern metaclasses) as keyword arguments. This should not be done.
As a second change, the new ``type.__init__`` just ignores keyword arguments. Currently, it insists that no keyword arguments are given. This leads to a (wanted) error if one gives keyword arguments to a class declaration if the metaclass does not process them. Metaclass authors that do want to accept keyword arguments must filter them out by overriding ``__init___``.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
Rejected Design Options =======================
Calling the hook on the class itself ------------------------------------
Adding an ``__autodecorate__`` hook that would be called on the class itself was the proposed idea of PEP 422. Most examples work the same way or even better if the hook is called on the subclass. In general, it is much easier to explicitly call the hook on the class in which it is defined (to opt-in to such a behavior) than to opt-out, meaning that one does not want the hook to be called on the class it is defined in.
This becomes most evident if the class in question is designed as a mixin: it is very unlikely that the code of the mixin is to be executed for the mixin class itself, as it is not supposed to be a complete class on its own.
The original proposal also made major changes in the class initialization process, rendering it impossible to back-port the proposal to older Python versions.
More importantly, having a pure Python implementation allows us to take two preliminary steps before before we actually change the interpreter, giving us the chance to iron out all possible wrinkles in the API.
Other variants of calling the hook ----------------------------------
Other names for the hook were presented, namely ``__decorate__`` or ``__autodecorate__``. This proposal opts for ``__init_subclass__`` as it is very close to the ``__init__`` method, just for the subclass, while it is not very close to decorators, as it does not return the class.
Requiring an explicit decorator on ``__init_subclass__`` --------------------------------------------------------
One could require the explicit use of ``@classmethod`` on the ``__init_subclass__`` decorator. It was made implicit since there's no sensible interpretation for leaving it out, and that case would need to be detected anyway in order to give a useful error message.
This decision was reinforced after noticing that the user experience of defining ``__prepare__`` and forgetting the ``@classmethod`` method decorator is singularly incomprehensible (particularly since PEP 3115 documents it as an ordinary method, and the current documentation doesn't explicitly say anything one way or the other).
A more ``__new__``-like hook ----------------------------
In PEP 422 the hook worked more like the ``__new__`` method than the ``__init__`` method, meaning that it returned a class instead of modifying one. This allows a bit more flexibility, but at the cost of much harder implementation and undesired side effects.
Adding a class attribute with the attribute order -------------------------------------------------
This got its own PEP 520.
History =======
This used to be a competing proposal to PEP 422 by Nick Coghlan and Daniel Urban. PEP 422 intended to achieve the same goals as this PEP, but with a different way of implementation. In the meantime, PEP 422 has been withdrawn favouring this approach.
References ==========
.. _more than 10 years ago: http://mail.python.org/pipermail/python-dev/2001-November/018651.html
.. _Zope's ExtensionClass: http://docs.zope.org/zope_secrets/extensionclass.html
Copyright =========
This document has been placed in the public domain.
.. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
On 14 July 2016 at 08:46, Guido van Rossum <guido@python.org> wrote:
On Wed, Jul 13, 2016 at 7:15 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Another small change should be noted here: in the current implementation of CPython, ``type.__init__`` explicitly forbids the use of keyword arguments, while ``type.__new__`` allows for its attributes to be shipped as keyword arguments. This is weirdly incoherent, and thus the above code forbids that. While it would be possible to retain the current behavior, it would be better if this was fixed, as it is probably not used at all: the only use case would be that at metaclass calls its ``super().__new__`` with *name*, *bases* and *dict* (yes, *dict*, not *namespace* or *ns* as mostly used with modern metaclasses) as keyword arguments. This should not be done.
As a second change, the new ``type.__init__`` just ignores keyword arguments. Currently, it insists that no keyword arguments are given. This leads to a (wanted) error if one gives keyword arguments to a class declaration if the metaclass does not process them. Metaclass authors that do want to accept keyword arguments must filter them out by overriding ``__init___``.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
It would be worth spelling out the end result of the new behaviour in the PEP to make sure it's what we want. Trying to reason about how that code works is difficult, but looking at some class definition scenarios and seeing how they behave with the old semantics and the new semantics should be relatively straightforward (and they can become test cases for the revised implementation). The basic scenario to cover would be defining a metaclass which *doesn't* accept any additional keyword arguments and seeing how it fails when passed an unsupported parameter: class MyMeta(type): pass class MyClass(metaclass=MyMeta, otherarg=1): pass MyMeta("MyClass", (), otherargs=1) import types types.new_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1)) types.prepare_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1)) Current behaviour:
class MyMeta(type): ... pass ... class MyClass(metaclass=MyMeta, otherarg=1): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type() takes 1 or 3 arguments MyMeta("MyClass", (), otherargs=1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Required argument 'dict' (pos 3) not found import types types.new_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib64/python3.5/types.py", line 57, in new_class return meta(name, bases, ns, **kwds) TypeError: type() takes 1 or 3 arguments types.prepare_class("MyClass", (), dict(metaclass=MyMeta, otherarg=1)) (<class '__main__.MyMeta'>, {}, {'otherarg': 1})
The error messages may change, but the cases which currently fail should continue to fail with TypeError Further scenarios would then cover the changes needed to the definition of "MyMeta" to make the class creation invocations above actually work (since the handling of __prepare__ already tolerates unknown arguments). First, just defining __new__ (which currently fails):
class MyMeta(type): ... def __new__(cls, name, bases, namespace, otherarg): ... self = super().__new__(cls, name, bases, namespace) ... self.otherarg = otherarg ... return self ... class MyClass(metaclass=MyMeta, otherarg=1): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type.__init__() takes no keyword arguments
Making this work would be fine, and that's what I believe will happen with the PEP's revised semantics. Then, just defining __init__ (which also fails):
class MyMeta(type): ... def __init__(self, name, bases, namespace, otherarg): ... super().__init__(name, bases, namespace) ... self.otherarg = otherarg ... class MyClass(metaclass=MyMeta, otherarg=1): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: type() takes 1 or 3 arguments
The PEP shouldn't result in any changes in this case. And finally defining both of them (which succeeds):
class MyMeta(type): ... def __new__(cls, name, bases, namespace, otherarg): ... self = super().__new__(cls, name, bases, namespace) ... self.otherarg = otherarg ... return self ... def __init__(self, name, bases, namespace, otherarg): ... super().__init__(name, bases, namespace) ... class MyClass(metaclass=MyMeta, otherarg=1): ... pass ... MyClass.otherarg 1
From a documentation perspective, one subtlety we should highlight is
That last scenario is the one we need to ensure keeps working (and I believe it does with Martin's current implementation) that the invocation order during subtype creation is: * mcl.__new__ - descr.__set_name__ - cls.__init_subclass__ * mcl.__init__ So if the metaclass defines both __new__ and __init__ methods, the new hooks will run before the __init__ method does. (I think that's fine, the docs just need to make it clear that type.__new__ is the operation doing the heavy lifting) Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
Hi Nick, hi list,
It would be worth spelling out the end result of the new behaviour in the PEP to make sure it's what we want. Trying to reason about how that code works is difficult, but looking at some class definition scenarios and seeing how they behave with the old semantics and the new semantics should be relatively straightforward (and they can become test cases for the revised implementation).
I agree with that. All the examples that Nick gives should work the same way as they used to. I'll turn them into tests. I hope it is fine if the error messages change slightly, as long as the error type stays the same? Let's look at an example that won't work anymore if my proposal goes throught: class MyType(type): def __new__(cls, name, bases, namespace): return super().__new__(cls, name=name, bases=bases, dict=namespace) I guess this kind of code is pretty rare. Note that I need to call the third parameter dict, as this is how it is named. Even if there is code out there like that, it would be pretty easy to change. Just in case someone wondered: def __new__(cls, **kwargs): return super().__new__(cls, **kwargs) doesn't work now and won't work afterwards, as the interpreter calls the metaclass with positional arguments. That said, it would be possible, at the cost of quite some lines of code, to make it fully backwards compatible. If the consensus is that this is needed, I'll change the PEP and code accordingly. My proposal also has the advantage that name, bases and dict may be used as class keyword arguments. At least for name I see a usecase: class MyMangledClass(BaseClass, name="Nice class name"): pass Greetings Martin
Hi Guido, Hi list, Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53 Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here: https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py), the test runs on older Pythons. But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic. Greetings Martin P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works?
I just reviewed the changes you made, I like __set_name__(). I'll just wait for your next update, incorporating Nick's suggestions. Regarding who merges PRs to the PEPs repo, since you are the author the people who merge don't pass any judgment on the changes (unless it doesn't build cleanly or maybe if they see a typo). If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it. I think the substantial discussion about the PEP should remain here in python-dev; comments about typos, grammar and other minor editorial issues can go on GitHub. Hope this part of the process makes sense! On Thu, Jul 14, 2016 at 6:50 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi list,
Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53
Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here: https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py), the test runs on older Pythons.
But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic.
Greetings
Martin
P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works? _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 07/14/2016 11:47 AM, Guido van Rossum wrote:
If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
FWIW, I often use a Github label, "don't merge" (colored red for urgency), to indicate that PRs are still in discussion stage: removing it is a lightweight way to signify that blocking issues have been resolved (in the opinion of the owner/matintainer, anyway). Tres. - -- =================================================================== Tres Seaver +1 540-429-0999 tseaver@palladion.com Palladion Software "Excellence by Design" http://palladion.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAEBAgAGBQJXh9P8AAoJEPKpaDSJE9HYsC0QAMPf/J+n35fg7sMjy07/fE8v xXXc+JbqnphnZolX1Xjla8sUD6tSpq0dp234VYeGwm4z19p3U5SYpYX4zzNuYCwE V2AVfdNpY0xwTkoFCbxXTwikZVIGt6o8IQLvqcjlQpCj3wl5A0ggcoaYDnXeKrZd wE4MF4t9YFgdABZ2i2RVbZNoSRUcMa1kKq9BKpnLnq65dPv2yAYQDDbWIatXLLbi 7kxAfK4CjSWR8BKNzo71uJDeVJVyk6N2nWLuGNOEff8BVZe83cG/2SRjRGALSb0h kV6FdPhwIhoZ+KrVvkLcbJYpUykBAPK68VSnomXNU14jpY9a3zqEIrirB4YLM3tS 9Ov2GYH+AhDPQ840B197mmkGN4nu/d52jCHPfecgccz2gooy+qoK3FRrMlshTTaD dbnTlNm/mkEBad8dz7l/u7cGvVG+k5AiFCGkOMikg4So0xXw7C9ulCQhoARWa0DS J0gTqEGHzGqYAwMXvWxobvlm3HxcxutWuYYx7vD0DRKrPRdpz/ELE7XpOh5bPjjU sEpt7gaAn/q962QorCDRopvqgd7MeRkrAdPKJzhCIeSUp9+Y/oqolZ/my4uEXSju W8WHWx41ioDvoUEHFW3pYljSN075STP21SCuxJh+GBDOVS2HsMXEb09wxM81GOAt V/mBLuZeptsVMiVSQk6J =/KS/ -----END PGP SIGNATURE-----
On Thu, 14 Jul 2016 at 11:05 Tres Seaver <tseaver@palladion.com> wrote:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
On 07/14/2016 11:47 AM, Guido van Rossum wrote:
If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
FWIW, I often use a Github label, "don't merge" (colored red for urgency), to indicate that PRs are still in discussion stage: removing it is a lightweight way to signify that blocking issues have been resolved (in the opinion of the owner/matintainer, anyway).
Just start the title with `[WIP]` and it will be obvious that it's a work-in-progress (it's a GitHub idiom).
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 07/14/2016 02:10 PM, Brett Cannon wrote:
On Thu, 14 Jul 2016 at 11:05 Tres Seaver <tseaver@palladion.com> wrote:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
On 07/14/2016 11:47 AM, Guido van Rossum wrote:
If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
FWIW, I often use a Github label, "don't merge" (colored red for urgency), to indicate that PRs are still in discussion stage: removing it is a lightweight way to signify that blocking issues have been resolved (in the opinion of the owner/matintainer, anyway).
Just start the title with `[WIP]` and it will be obvious that it's a work-in-progress (it's a GitHub idiom).
De gustibus, I guess: unlike the title, labels stay visible no matter how one scrolls the PR / issue, and they are more easily searchable. Tres. - -- =================================================================== Tres Seaver +1 540-429-0999 tseaver@palladion.com Palladion Software "Excellence by Design" http://palladion.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1 iQIcBAEBAgAGBQJXh90aAAoJEPKpaDSJE9HYeFMP/3r+b6MP4VI+SLnPT6PeZdHU aVn9/bz4hMb4DtIB1adp6CBEdtxijg0Y2H6BgcmnoFcqhVO0yXquOtJmVfqQr44T zO8DY+v+eVBcw8KX5MduQt3jLq8fBXviFq0yu55bWYboQRKbUKrfzFwZFlZJ9gH7 AAdieX/26NK4RkFxePYn5dJeJ1EIX7RoRuIB8X5NPve6FA08eRUHvSicQN4Vpvey Xs+eiLcz+3pOHCu4hiERInu19lztoL5GmdC+cL3mq2A9qpKy9fEAWVRhU84VaDa1 86/jKXgoXfZt2wH7Wj/MC6Z8gXMutIyjcrjVyZEbPQe4zt5o5Vdv/M9nxk1iOnV3 sSqY72HQiiaWvwjWasv0F78LT0nKqt9+bq+aBHrF5PHd0epxInI7KQEScuB+BcaS aNNVZtSRRQhCEnO8MB6cedBv90sg2FVv8ITBNHac/Zn2ThljMJ8s90gHZZbC3T6/ uP0uvwS8aYzKJoTH5Mmxvt4m4vQCg+tintOwF8/nwN4y4kQFXZcCZqeb4l55XRAE INal/Khx0eHqd07D7BRZ/a1lKTDuyEuTifJNjZjr9fC704xplMTygJc/kuaTvMfN 4e30iKbMO4oJ3Oyrysr/2E81YlqBe9ZMGdkdBwvyYmGnIKXbmlsHHUQn1asRwF64 l5HJUWDAWxccJ8d83q0g =NdlU -----END PGP SIGNATURE-----
Hi Guido, Hi Nick, Hi list, so I just updated PEP 487, you can find it here: https://github.com/python/peps/pull/57 if it hasn't already been merged. There are no substantial updates there, I only updated the wording as suggested, and added some words about backwards compatibility as hinted by Nick. Greetings Martin 2016-07-14 17:47 GMT+02:00 Guido van Rossum <guido@python.org>:
I just reviewed the changes you made, I like __set_name__(). I'll just wait for your next update, incorporating Nick's suggestions. Regarding who merges PRs to the PEPs repo, since you are the author the people who merge don't pass any judgment on the changes (unless it doesn't build cleanly or maybe if they see a typo). If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
I think the substantial discussion about the PEP should remain here in python-dev; comments about typos, grammar and other minor editorial issues can go on GitHub. Hope this part of the process makes sense!
On Thu, Jul 14, 2016 at 6:50 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi list,
Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53
Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here: https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py), the test runs on older Pythons.
But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic.
Greetings
Martin
P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works? _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
This PEP is now accepted for inclusion in Python 3.6. Martin, congratulations! Someone (not me) needs to review and commit your changes, before September 12, when the 3.6 feature freeze goes into effect (see https://www.python.org/dev/peps/pep-0494/#schedule). On Sun, Jul 17, 2016 at 4:32 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi Nick, Hi list,
so I just updated PEP 487, you can find it here: https://github.com/python/peps/pull/57 if it hasn't already been merged. There are no substantial updates there, I only updated the wording as suggested, and added some words about backwards compatibility as hinted by Nick.
Greetings
Martin
2016-07-14 17:47 GMT+02:00 Guido van Rossum <guido@python.org>:
I just reviewed the changes you made, I like __set_name__(). I'll just wait for your next update, incorporating Nick's suggestions. Regarding who merges PRs to the PEPs repo, since you are the author the people who merge don't pass any judgment on the changes (unless it doesn't build cleanly or maybe if they see a typo). If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
I think the substantial discussion about the PEP should remain here in python-dev; comments about typos, grammar and other minor editorial issues can go on GitHub. Hope this part of the process makes sense!
On Thu, Jul 14, 2016 at 6:50 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi list,
Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53
Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here: https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py), the test runs on older Pythons.
But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic.
Greetings
Martin
P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works? _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
Great job, Martin! Thanks for seeing this through. :) -eric On Sun, Jul 17, 2016 at 10:57 AM, Guido van Rossum <guido@python.org> wrote:
This PEP is now accepted for inclusion in Python 3.6. Martin, congratulations! Someone (not me) needs to review and commit your changes, before September 12, when the 3.6 feature freeze goes into effect (see https://www.python.org/dev/peps/pep-0494/#schedule).
On Sun, Jul 17, 2016 at 4:32 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi Nick, Hi list,
so I just updated PEP 487, you can find it here: https://github.com/python/peps/pull/57 if it hasn't already been merged. There are no substantial updates there, I only updated the wording as suggested, and added some words about backwards compatibility as hinted by Nick.
Greetings
Martin
2016-07-14 17:47 GMT+02:00 Guido van Rossum <guido@python.org>:
I just reviewed the changes you made, I like __set_name__(). I'll just wait for your next update, incorporating Nick's suggestions. Regarding who merges PRs to the PEPs repo, since you are the author the people who merge don't pass any judgment on the changes (unless it doesn't build cleanly or maybe if they see a typo). If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
I think the substantial discussion about the PEP should remain here in python-dev; comments about typos, grammar and other minor editorial issues can go on GitHub. Hope this part of the process makes sense!
On Thu, Jul 14, 2016 at 6:50 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi list,
Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53
Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here: https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py), the test runs on older Pythons.
But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic.
Greetings
Martin
P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works? _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido) _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/ericsnowcurrently%40gmail...
Yes, I'm very excited about this! Will this mean no more metaclass conflicts if using @abstractmethod? On Sun, Jul 17, 2016 at 12:59 PM Guido van Rossum <guido@python.org> wrote:
This PEP is now accepted for inclusion in Python 3.6. Martin, congratulations! Someone (not me) needs to review and commit your changes, before September 12, when the 3.6 feature freeze goes into effect (see https://www.python.org/dev/peps/pep-0494/#schedule).
On Sun, Jul 17, 2016 at 4:32 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi Nick, Hi list,
so I just updated PEP 487, you can find it here: https://github.com/python/peps/pull/57 if it hasn't already been merged. There are no substantial updates there, I only updated the wording as suggested, and added some words about backwards compatibility as hinted by Nick.
Greetings
Martin
2016-07-14 17:47 GMT+02:00 Guido van Rossum <guido@python.org>:
I just reviewed the changes you made, I like __set_name__(). I'll just wait for your next update, incorporating Nick's suggestions. Regarding who merges PRs to the PEPs repo, since you are the author the people who merge don't pass any judgment on the changes (unless it doesn't build cleanly or maybe if they see a typo). If you intend a PR as a base for discussion you can add a comment saying e.g. "Don't merge yet". If you call out @gvanrossum, GitHub will make sure I get a message about it.
I think the substantial discussion about the PEP should remain here in python-dev; comments about typos, grammar and other minor editorial issues can go on GitHub. Hope this part of the process makes sense!
On Thu, Jul 14, 2016 at 6:50 AM, Martin Teichmann <lkb.teichmann@gmail.com> wrote:
Hi Guido, Hi list,
Thanks for the nice review! I applied followed up your ideas and put it into a github pull request: https://github.com/python/peps/pull/53
Soon we'll be working there, until then, some responses to your comments:
I wonder if this should be renamed to __set_name__ or something else that clarifies we're passing it the name of the attribute? The method name __set_owner__ made me assume this is about the owning object (which is often a useful term in other discussions about objects), whereas it is really about telling the descriptor the name of the attribute for which it applies.
The name for this has been discussed a bit already, __set_owner__ was Nick's idea, and indeed, the owner is also set. Technically, __set_owner_and_name__ would be correct, but actually I like your idea of __set_name__.
That (inheriting type from type, and object from object) is very confusing. Why not just define new classes e.g. NewType and NewObject here, since it's just pseudo code anyway?
Actually, it's real code. If you drop those lines at the beginning of the tests for the implementation (as I have done here:
https://github.com/tecki/cpython/blob/pep487b/Lib/test/test_subclassinit.py ),
the test runs on older Pythons.
But I see that my idea to formulate things here in Python was a bad idea, I will put the explanation first and turn the code into pseudo-code.
def __init__(self, name, bases, ns, **kwargs): super().__init__(name, bases, ns)
What does this definition of __init__ add?
It removes the keyword arguments. I describe that in prose a bit down.
class object: @classmethod def __init_subclass__(cls): pass
class object(object, metaclass=type): pass
Eek! Too many things named object.
Well, I had to do that to make the tests run... I'll take that out.
In the new code, it is not ``__init__`` that complains about keyword arguments, but ``__init_subclass__``, whose default implementation takes no arguments. In a classical inheritance scheme using the method resolution order, each ``__init_subclass__`` may take out it's keyword arguments until none are left, which is checked by the default implementation of ``__init_subclass__``.
I called this out previously, and I am still a bit uncomfortable with the backwards incompatibility here. But I believe what you describe here is the compromise proposed by Nick, and if that's the case I have peace with it.
No, this is not Nick's compromise, this is my original. Nick just sent another mail to this list where he goes a bit more into the details, I'll respond to that about this topic.
Greetings
Martin
P.S.: I just realized that my changes to the PEP were accepted by someone else than Guido. I am a bit surprised about that, but I guess this is how it works? _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido)
Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/guido%40python.org
-- --Guido van Rossum (python.org/~guido) _______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/mistersheik%40gmail.com
On 19 July 2016 at 09:26, Neil Girdhar <mistersheik@gmail.com> wrote:
Yes, I'm very excited about this!
Will this mean no more metaclass conflicts if using @abstractmethod?
ABCMeta and EnumMeta both create persistent behavioural differences rather than only influencing subtype definition, so they'll need to remain as custom metaclasses. What this PEP (especially in combination with PEP 520) is aimed at enabling is subclassing APIs designed more around the notion of "implicit class decoration" where a common base class or mixin can be adjusted to perform certain actions whenever a new subclass is defined, without changing the runtime behaviour of those subclasses. (For example: a mixin or base class may require that certain parameters be set as class attributes - this PEP will allow the base class to check for those and throw an error at definition time, rather than getting a potentially cryptic error when it attempts to use the missing attribute) Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
Yes, I see what you're saying. However, I don't understand why __init_subclass__ (defined on some class C) cannot be used to implement the checks required by @abstractmethod instead of doing it in ABCMeta. This would prevent metaclass conflicts since you could use @abstractmethod with any metaclass or no metaclass at all provided you inherit from C. On Tue, Jul 19, 2016 at 12:21 AM Nick Coghlan <ncoghlan@gmail.com> wrote:
On 19 July 2016 at 09:26, Neil Girdhar <mistersheik@gmail.com> wrote:
Yes, I'm very excited about this!
Will this mean no more metaclass conflicts if using @abstractmethod?
ABCMeta and EnumMeta both create persistent behavioural differences rather than only influencing subtype definition, so they'll need to remain as custom metaclasses.
What this PEP (especially in combination with PEP 520) is aimed at enabling is subclassing APIs designed more around the notion of "implicit class decoration" where a common base class or mixin can be adjusted to perform certain actions whenever a new subclass is defined, without changing the runtime behaviour of those subclasses. (For example: a mixin or base class may require that certain parameters be set as class attributes - this PEP will allow the base class to check for those and throw an error at definition time, rather than getting a potentially cryptic error when it attempts to use the missing attribute)
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
On 19 July 2016 at 16:41, Neil Girdhar <mistersheik@gmail.com> wrote:
Yes, I see what you're saying. However, I don't understand why __init_subclass__ (defined on some class C) cannot be used to implement the checks required by @abstractmethod instead of doing it in ABCMeta. This would prevent metaclass conflicts since you could use @abstractmethod with any metaclass or no metaclass at all provided you inherit from C.
ABCMeta also changes how __isinstance__ and __issubclass__ work and adds additional methods (like register()), so enabling the use of @abstractmethod without otherwise making the type an ABC would be very confusing behaviour that we wouldn't enable by default. But yes, this change does make it possible to write a mixin class that implements the "@abstractmethod instances must all be overridden to allow instances to to be created" logic from ABCMeta without otherwise turning the class into an ABC instance. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
Thanks for clarifying. On Tue, Jul 19, 2016 at 10:34 AM Nick Coghlan <ncoghlan@gmail.com> wrote:
Yes, I see what you're saying. However, I don't understand why __init_subclass__ (defined on some class C) cannot be used to implement
On 19 July 2016 at 16:41, Neil Girdhar <mistersheik@gmail.com> wrote: the
checks required by @abstractmethod instead of doing it in ABCMeta. This would prevent metaclass conflicts since you could use @abstractmethod with any metaclass or no metaclass at all provided you inherit from C.
ABCMeta also changes how __isinstance__ and __issubclass__ work and adds additional methods (like register()), so enabling the use of @abstractmethod without otherwise making the type an ABC would be very confusing behaviour that we wouldn't enable by default.
But yes, this change does make it possible to write a mixin class that implements the "@abstractmethod instances must all be overridden to allow instances to to be created" logic from ABCMeta without otherwise turning the class into an ABC instance.
Cheers, Nick.
-- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia
participants (8)
-
Brett Cannon
-
Eric Snow
-
Ethan Furman
-
Guido van Rossum
-
Martin Teichmann
-
Neil Girdhar
-
Nick Coghlan
-
Tres Seaver