Hello,
This is my first post on python-dev and I hope that I am not breaking any rule.
I wanted to react on the discussion regarding PEP487.
This year, we have been working on a refactoring of the `traitlets` library, an implementation of the descriptor pattern that is used in Project Jupyter / IPython. The motivations for the refactoring was similar to those of this PEP: having a more generic metaclass allowing more flexibility in terms of types of descriptors, in order to avoid conflicts between meta classes.
We ended up with:
- A metaclass called MetaHasDescriptor
- A base class of meta MetaHasDescriptor named HasDescriptors
Usage:
class MyClass(HasDescriptors):
attr = DesType()
DesType inherits from a base Descriptor type. The key is that their initialization is done in three stages
- the main
DesType.__init__
- the part of the initialization of DesType that depends on the definition of MyClass
DesType.class_init(self, cls, name)
which is called from MetaHasDescriptors.__new__
- a method of DesType that depends on the definition of instances of MyClass
DesType.instance_init(self, obj)
which is called from HasDescriptors.__new__.
instance_init, may make modifications on the HasDescriptors instance.
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__.
Thanks,
Sylvain
PS: thanks to Neil Girdhar for the heads up on the traitlets repo.