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

Nick Coghlan ncoghlan at gmail.com
Wed Jul 20 12:22:37 EDT 2016

Hi Sylvain,

Thanks for getting in touch! The traitlets library sounds interesting,
and provides good additional evidence that this is a capability that
folks are interested in having available.

On 20 July 2016 at 15:26, Sylvain Corlay <sylvain.corlay at gmail.com> wrote:
> My understanding is that the proposed __set_name__ in PEP487 exactly
> corresponds to our class_init, although interestingly we often do much more
> in class_init than setting the name of the descriptor, such as setting a
> this_class attribute or calling class_init on contained descriptors.
> Therefore I do not think that the names __set_name__ or __set_owner__ are
> appropriate for this use case.
> In a way, the long-form explicit names for our class_init and instance_init
> methods would be something like __init_fom_owner_class__, and
> __touch_instance__.

It's certainly a reasonable question/concern, but we've learned from
experience that we're better off using protocol method names that are
very specific to a particular intended use case, even if they can be
adapted for other purposes. The trick is that we want educators
teaching Python to be able to very easily answer the question of "What
is this special method for?" (even if they later go on to say "And
it's also used for these other things...")

One previous example of that is the __index__ protocol, where the
actual semantics are "instances of this type can be losslessly
converted to integers", but the protocol is named for the particular
use case "instances of this type can be used as sequence indices".

For PEP 487, the two operations guiding the naming of the methods are
"notify a base class when a new subclass is defined" and "notify a
descriptor of its attribute name when assigned to a class". The
precise verbs then mirror those already used in other parts of the
related protocols (with __init__ leading to __init_subclass__, and
__set__ leading to __set_name__).

The main capability that __set_name__ provides that was previously
difficult is letting a descriptor know its own name in the class
namespace. The fact a descriptor implementor can do anything else they
want as a side-effect of that new method being called isn't
substantially different from the ability to add side-effects to the
existing __get__, __set__ and __delete__ protocol methods.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list