Pass parameters/globals to eval

esandin at gmail.com esandin at gmail.com
Fri Nov 23 13:14:25 CET 2012


I am trying to set the parameter 'a' below so that it can be used when I call eval:

>>> def gp_function():
...     return 1+a
... 
>>> print eval("gp_function()", {'a':123, 'gp_function':gp_function})

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
  File "<stdin>", line 2, in a_method
NameError: global name 'a' is not defined

Why isn't 'a' defined?
Shouldn't you be able to define the global variables with a dict passed to eval?
Is there an other way to do this, beside the two obvious: defining 'a' before calling gp_function and using a as an argument in gp_function?

In case you are wondering why I want this:
This is a simplification of a problem I ran into when experimenting with pyevolve. After running pyevolve: GTreeGP.getCompiledCode() I get some compiled code, and need to pass some arguments to it. Perhaps there is an easier way to do it...

Kind Regards
Emil


More information about the Python-list mailing list