running a function in a different scope

Uwe Mayer merkosh at hadiko.de
Fri May 14 17:37:41 EDT 2004


Hi,

I've got a class that receives a function in the constructor and uses the
__call__ method to execute the aforementioned function when the instance
object is called:

class foo(object):
  def __init__(self, func):
    self.func = func
  def __call__(self, *arg, **kwarg):
    return self.func(*arg, **kwarg)

This is ok until I reassign i.e. the builtin function "vars":
>>> vars = foo(vars)
{'self': <__main__.foo object at 0x401ee78c>, 'kwarg': {}, 'arg': ()}

instead of the scope:
{'__builtins__': <module '__builtin__' (built-in)>, '__file__':
'/home/merkosh/.pythonrc', 'sys': <module 'sys' (built-in)>, '__name__':
'__main__', 'foo': <class '__main__.foo'>, '__doc__': None}

Now the function "vars" does not bother me that much.  I wonder which other
side-effects will occur, which functions may not be called from within a
foo-object and perhaps how to avoid this, i.e. can the foo-instance detect
in which scope it was executed and call the passed function (vars) in that
particular scope?

Thanks for any hints.
Ciao
Uwe



More information about the Python-list mailing list