__getattr__-like method for current module.

Christian Hudon chrish at debian.org
Mon Aug 16 21:59:44 CEST 2004


Hi,

I'd like to be able to trap lookups of attributes of the current module. 
Exactly like what __getattr__ does, but for modules. As an exmaple, I'd 
like to be able to do:

File foo.py

enable_magic()

def foo():
     undefined_function(1, 2)

and then when I call foo.foo from somewhere else, the lookup of the 
undefined undefined_function symbol is trapped and I can (say) 
dynamically define and return a function.

I know about the trick of defining a class instance that has a 
__getattr__ that does what you want and overwriting the entry for the 
module in sys.modules, but that only works when accessing that module 
from the outside. So in the example, my undefined_function call would 
have to be prefixed by the name of the magic module.

I tried building a subclass of module and installing that before all the 
def and class in the module are executed. I tried injecting a 
__getattr__ method in the globals dict of the module. I tried a bunch of 
other things that I forgot... None of these work (or at least I couldn't 
make them work). Among other things, it seems that the module part of 
Python is quite a bit less dynamic than the rest of the language. 
(Although I'd be happy to be proved wrong.)

Any way of doing what I want to do?

   Christian




More information about the Python-list mailing list