eval and dict

Anton Muhin antonmuhin at sendmail.ru
Thu May 22 10:20:06 EDT 2003


Here is an example that might be of interest for you (warning: I'm not 
an expert and a lot of bugs can be here):

class CallStub(object):
     def __init__(self, obj):
         self.__obj = obj

     def __call__(self, *args, **kwargs):
         print "CallStub()", args, kwargs
         return self.__obj(*args, **kwargs)

def f(x):
     print "f"
     return x

def g(xxx):
     print "g"
     return 2*xxx

def print_dict(d):
     print ", ".join(d)

expr = "x = f(3) + f(x = 4) + g(xxx = 1)"
code_block = compile(expr, "", "single")

my_dict = {}
globs = globals()

for name in code_block.co_names:
     if name in globs:
         obj = globs[name]
         if callable(obj):
             my_dict[name] = CallStub(obj)
         else:
             my_dict[name] = obj

print "results:",
print_dict(my_dict)

exec code_block in my_dict

print "executed:",
print_dict(my_dict)
print my_dict['x']


Executes to:

 >pythonw -u proxy.py
results: g, f
CallStub() (3,) {}
f
CallStub() () {'x': 4}
f
CallStub() () {'xxx': 1}
g
executed: __builtins__, x, g, f
9

anton.






More information about the Python-list mailing list