passing a custom locals to a function
Steven Taschuk
staschuk at telusplanet.net
Fri May 23 20:04:40 EDT 2003
Quoth Kuzminski, Stefan R:
> I'm trying to allow for variables in a dictionary to be manipulated
> directly ( without specifying the dictionary ) by putting the values in
> the local namespace. The end result for the users of the tool I'm
> creating is that they can fill in the body of the 'work' function below
> with more natural syntax ( var1 + var2 rather than dict['var1'] +
> dict['var2] )
[...]
> This works but is too slow ( and is a bit of a kludge getting the locals
> back into the dict because of extra things that might be in locals I
> don't want in the dict such as self ). I tried to eval and exec passing
> locals explicitly, but if I point exec to a function, the locals don't
> seem to show up inside the function..
As Alex explained, fiddling with the locals of a function will be
difficult.
You could instead consider the user's code to be a module rather
than the body of a function, and use your dict for the globals in
that module. That is, let your users write a file such as
# userfile.py
a, b = a+b, a
and then invoke it with
>>> vars = {'a': 8, 'b': 5}
>>> execfile('userfile.py', vars)
>>> del vars['__builtins__']
>>> vars
{'a': 13, 'b': 8}
or
>>> source = file('userfile.py').read()
>>> exec source in vars
>>> del vars['__builtins__']
>>> vars
{'a': 21, 'b': 13}
or some such.
--
Steven Taschuk staschuk at telusplanet.net
"I tried to be pleasant and accommodating, but my head
began to hurt from his banality." -- _Seven_ (1996)
More information about the Python-list
mailing list