[Python-Dev] PEP 549 v2: now titled Instance Descriptors

Nathaniel Smith njs at pobox.com
Fri Sep 8 16:54:22 EDT 2017


On Fri, Sep 8, 2017 at 1:45 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 09/08/2017 12:44 PM, Larry Hastings wrote:
>
>> I've updated PEP 549 with a new title--"Instance Descriptors" is a better
>> name than "Instance Properties"--and to
>> clarify my rationale for the PEP.  I've also updated the prototype with
>> code cleanups and a new type:
>> "collections.abc.InstanceDescriptor", a base class that allows user
>> classes to be instance descriptors.
>
>
> I like the new title, I'm +0 on the PEP itself, and I have one correction
> for the PEP:  we've had the ability to simulate module properties for ages:
>
>     Python 2.7.6 (default, Oct 26 2016, 20:32:47)
>     [GCC 4.8.4] on linux2
>     Type "help", "copyright", "credits" or "license" for more information.
>     --> import module_class
>     --> module_class.hello
>     'hello'
>     --> module_class.hello = 'hola'
>     --> module_class.hello
>     'hola'
>
> And the code:
>
>     class ModuleClass(object):
>         @property
>         def hello(self):
>             try:
>                 return self._greeting
>             except AttributeError:
>                 return 'hello'
>         @hello.setter
>         def hello(self, value):
>             self._greeting = value
>
>     import sys
>     sys.modules[__name__] = ModuleClass()
>
> I will admit I don't see what reassigning the __class__ attribute on a
> module did for us.

If you have an existing package that doesn't replace itself in
sys.modules, then it's difficult and risky to switch to that form --
don't think of toy examples, think of django/__init__.py or
numpy/__init__.py. You have to rewrite the whole export logic, and you
have to figure out what to do with things like submodules that import
from the parent module before the swaparoo happens, you can get skew
issues between the original module namespace and the replacement class
namespace, etc. The advantage of the __class__ assignment trick (as
compared to what we had before) is that it lets you easily and safely
retrofit this kind of magic onto existing packages.

-n

-- 
Nathaniel J. Smith -- https://vorpus.org


More information about the Python-Dev mailing list