__getattr__-like method for current module.

C

Christian Hudon

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top