changing local namespace of a function

Kent Johnson kent3737 at yahoo.com
Sat Feb 5 11:16:29 EST 2005


Bo Peng wrote:
> Yes. I thought of using exec or eval. If there are a dozen statements,
> 
> def fun(d):
>   exec 'z = x + y' in globals(), d
> 
> seems to be more readable than
> 
> def fun(d):
>   d['z'] = d['x'] + d['y']
> 
> But how severe will the performance penalty be?

You can precompile the string using compile(), you only have to do this once.

  >>> def makeFunction(funcStr, name):
  ...   code = compile(funcStr, name, 'exec')
  ...   def f(d):
  ...     exec code in d
  ...     del d['__builtins__'] # clean up extra entry in d
  ...   return f
  ...
  >>> f = makeFunction('z = x + y', 'f')
  >>> a = {'x':1, 'y':2}
  >>> b = {'x':3, 'y':3}
  >>> f(a)
  >>> a
{'y': 2, 'x': 1, 'z': 3}
  >>> f(b)
  >>> b
{'y': 3, 'x': 3, 'z': 6}



More information about the Python-list mailing list