namespaces

Bengt Richter bokr at oz.net
Tue Aug 9 14:18:38 EDT 2005


On Tue, 09 Aug 2005 08:35:38 -0700, Scott David Daniels <Scott.Daniels at Acm.Org> wrote:

>Paolino wrote:
>> Peter Otten wrote:
>>> Paolino wrote:
>>>> Why descriptor mechanism doesn't apply to modules?
>>> Because modules are instances of the module class and the descriptor 
>>> has to be defined in the class in order to work with the instance....
>> Then there is no way of having descriptors at module level,as 'module' 
>> class is not updatable.
>
>Well, an entry in the dictionary "sys.modules" is what is returned by
>imports, so you could either pre-replace or post-replace a module by
>an object which uses the descriptor technique to get to some (but not
>necessarily all) of the attributes.  Think of this technique as a
>hack to get to a goal, rather than a good technique to use; good for
>debugging, not so nice for production work.  If you still don't know
>how to do this from this admittedly sketchy description, I'd suggest
>you avoid trying it altogether.
>
I had the thought a while ago that it might be interesting to have
an import variant that could produce a subclassed module, where you
indicate the import name as usual (for __import__) and also supply
the subclass source text as an argument (string or file).
E.g., something like

    subclass_source = """\
    class MyModule(math):
        twopi = property(lambda: math.pi*2.0')
    """

    module_with_property = subclassing_import('math', subclass=subclass_source)

Another thought/bf would be a way to extend the attribute namespace of an arbitrary object
by chaining the attribute name spaces of a sequence of objects (this would be a language mod)
e.g., (sort of a dynamic instance attribute mixin)

     obj ..= a, b, c  # a sequence of objects

then

     obj.x  # looks for obj.x, then a.x then b.x then c.x before giving up with attribute error
     obj ..=()  # clears chained attribute name space ?

Then you could add a property to the namespace of a module by adding an object whose class defines
the property, like

     mod ..= objhavingproperty # same tuple ambiguity as with 'somestr' % x

something analogous to += on immutables would have to be done for builtin objects I suppose.

Just adding more mulch/worms to the idea garden ;-)

Regards,
Bengt Richter



More information about the Python-list mailing list