tags:

views:

144

answers:

1

I know how to override an object's getattr() to handle calls to undefined object functions. However, I would like to achieve the same behavior for the builtin getattr() function. For instance, consider code like this:

   call_some_undefined_function()

Normally, that simply produces an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'call_some_undefined_function' is not defined

I want to override getattr() so that I can intercept the call to "call_some_undefined_function()" and figure out what to do.

Is this possible?

Thanks,

--Steve

+1  A: 

I can only think of a way to do this by calling eval.

class Global(dict):
    def undefined(self, *args, **kargs):
        return u'ran undefined'

    def __getitem__(self, key):
        if dict.has_key(self, key):
            return dict.__getitem__(self, key)
        return self.undefined

src = """
def foo():
    return u'ran foo'

print foo()
print callme(1,2)
"""

code = compile(src, '<no file>', 'exec')

globals = Global()
eval(code, globals)

The above outputs

ran foo
ran undefined
Andrew E. Falcon