Exec is slow since compiling the string and calls to globals() use a lot of time. The last one is most elegant but __getattr__ and __setattr__ are costly. The 'evil hack' solution is good since accessing x and y takes no additional time.
Previous comparison was not completely fair since I could pre-compile fun2 and I used indirect __setattr__. Here is the new one:
>>> # solution two: use exec
... def makeFunction(funcStr, name):
... code = compile(funcStr, name, 'exec')
... def f(d):
... exec code in d
... return f
...
>>> def fun2(d):
... myfun = makeFunction('z = x + y', 'myfun')
... for i in xrange(0,N):
... myfun(d)
... del d['__builtins__']
You are still including the compile overhead in fun2. If you want to see how fast the compiled code is you should take the definition of myfun out of fun2:
myfun = makeFunction('z = x + y', 'myfun') def fun2(d): for i in xrange(0,N): myfun(d) del d['__builtins__']
Kent -- http://mail.python.org/mailman/listinfo/python-list