Callable modules?

holger krekel pyth at devel.trillke.net
Thu Jul 25 06:51:31 EDT 2002


Hi Bengt,

thanks for your nice code samples.  Although i had problems reading
code containing my name too often (Signal Overflow :-). 
Especially your experiments with putting the execution
of the module-file into a class makes some sense to me.  
Below i tried a similar yet different approach :-)

I really wonder whether there are *any* reasons to have 
a distinct ModuleType. What does it offer that a plain
good old (or new) 'class' could not do?

Anyway, here is one interesting small experiment ...


** start Module.py **
import __builtin__

class Module(object):
    oldimporter = __builtin__.__import__

    def __init__(self, name, globals={}, locals={}, fromlist=[]):
        module = self.oldimporter(name, globals, locals, fromlist)
        self.__dict__ = module.__dict__

    def __getattr__(self, name):
        getter = self.__dict__.get('__getattr__')
        return getter(name)

__builtin__.__import__ = Module

**end**

** test.py **
def __getattr__(name):
    print "__getattr__ called with name",name

import os,sys
**

and the sesssion with these experimental stuff:

>>> import Module   # wraps __import__
>>> import test
>>> test
<Module.Module object at 0x402e5b6c>
>>> test.os
<Module.Module object at 0x402f6d8c>
>>> test.h
__getattr__ called with name h

I wonder if there are any serious drawbacks of this approach.  

regards,

    holger




More information about the Python-list mailing list