[Python-ideas] Extend module objects to support properties

Nick Coghlan ncoghlan at gmail.com
Thu Jan 31 09:56:16 CET 2013


On Thu, Jan 31, 2013 at 2:42 AM, Larry Hastings <larry at hastings.org> wrote:
> Of those four issues, the latter two are wontfix.  Code that futzes with an
> object's __dict__ bypasses the property machinery but this is already viewed
> as acceptable.
>
> Obviously the point of the proposal is to change the behavior of the first
> two.  Whether this is manageable additional complexity, or fast enough,
> remains to be seen--which is why this is in ideas not dev.

Looking at the problem from a different direction:

Currently, modules are *instances* of a normal type
(types.ModuleType). Thus, anything stored in their global namespace is
like anything else stored in a normal instance dictionary: no
descriptor behaviour.

The request in this thread is basically for a way to:

1. Define a custom type
2. Put an instance of that type in sys.modules instead of the ordinary
module object

Now here's the thing: we already support this, because the import
system is designed to cope with modules replacing
"sys.modules[__name__]" while they're being loaded. The way this
happens is that, after we finish loading a module, we usually don't
trust what the loader gave us. Instead, we go look at what's in
sys.modules under the name being loaded.

So if, in your module code, you do this:

    import sys, types
    class MyPropertyUsingModule(types.ModuleType):
        def __init__(self, original):
            # Keep a reference to the original module to avoid the
            # destructive cleanup of the global namespace
            self._original = original

        @property
        def myglobal(self):
            return theglobal

        @myglobal.setter
        def myglobal(self, value):
            global theglobal
            theglobal = value

    sys.modules[__name__] = MyPropertyUsingModule(sys.modules[__name__])

Then what you end up with in sys.modules is a module with a global
property, "myglobal".

I'd prefer to upgrade this from "begrudged backwards compatibility
hack" to "supported feature", rather than doing anything more
complicated.

Cheers,
Nick.

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



More information about the Python-ideas mailing list