[Python-Dev] PEP 549: Instance Properties (aka: module properties)

Larry Hastings larry at hastings.org
Tue Sep 12 03:38:47 EDT 2017

On 09/11/2017 07:22 PM, Guido van Rossum wrote:
> I still don't follow. How does one use InstanceDescriptor?

If you write a class that inherits from InstanceDescriptor and supports 
the descriptor protocol, module objects will call the descriptor 
protocol functions when that object is accessed inside a module instance.

Example: if this is "module.py":

    import collections.abc
    class CustomInstanceProperty(collections.abc.InstanceDescriptor):
         def __get__(self, instance, owner):
             print("CustomInstanceProperty.__get__ called!")
             return 44

    cip = CustomInstanceProperty()

If you then "import module" and reference "module.cip", it'll print 
"CustomInstanceProperty.__get__ called!" and you'll get the value 44.  
All three magic methods for descriptors work fine.

(BTW, I didn't know the best way to make this work.  I wound up 
implementing InstanceDescriptor by copying-and-pasting 
PyBaseObject_Type, setting the special tp_flag, and ensuring the special 
flag gets propagated to subclasses in inherit_special().  If there's a 
better way to do it I'd happily improve the implementation.)

> Is this still about modules, or is it a generalization of properties 
> for non-module instances? (If it is specific to modules, why doesn't 
> it have "module" in its name? Or if it's not, why is it in this 
> discussion?)

It's a generalization of supporting descriptors for instances, but 
currently it's only supported by modules.  It's opt-in and modules are 
the only class doing so.

>     The prototype is linked to from the PEP; for your convenience
>     here's a link:
>         https://github.com/larryhastings/cpython/tree/module-properties
>         <https://github.com/larryhastings/cpython/tree/module-properties>
> I found that link in the PEP, but it's just a branch of a fork of 
> cpython. It would be easier to review the prototype as a PR to 
> upstream cpython.

Okay, I'll make a PR tomorrow and post a reply here (and update the PEP).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20170912/a43d0e92/attachment.html>

More information about the Python-Dev mailing list