PEP 487: Clarify "only on subclasses" decision (#64)

This commit is contained in:
Nick Coghlan 2016-07-30 17:04:03 +10:00 committed by GitHub
parent 2570c01992
commit 0839e9deb0
1 changed files with 18 additions and 5 deletions

View File

@ -382,11 +382,11 @@ 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.
way or even better if the hook is called only on strict subclasses. In general,
it is much easier to arrange to explicitly call the hook on the class in which it
is defined (to opt-in to such a behavior) than to opt-out (by remember to check for
``cls is __class`` in the hook body), 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
@ -397,6 +397,19 @@ The original proposal also made major changes in the class
initialization process, rendering it impossible to back-port the
proposal to older Python versions.
When it's desired to also call the hook on the base class, two mechanisms are available:
1. Introduce an additional mixin class just to hold the ``__init_subclass__``
implementation. The original "base" class can then list the new mixin as its
first parent class.
2. Implement the desired behaviour as an independent class decorator, and apply that
decorator explicitly to the base class, and then implicitly to subclasses via
``__init_subclass__``.
Calling ``__init_subclass__`` explicitly from a class decorator will generally be
undesirable, as this will also typically call ``__subclass_init__`` a second time on
the parent class, which is unlikely to be desired behaviour.
Other variants of calling the hooks
-----------------------------------