Pass parameters/globals to eval

E

esandin

I am trying to set the parameter 'a' below so that it can be used when I call eval:
.... return 1+a
....
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
 
C

Chris Angelico

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?

It is defined, but not in the context of the called function.

You defined that function in a particular scope, which then becomes
its global scope. (I'm handwaving a lot of details here. Bear with
me.) When you eval a bit of code, you define the global scope for
_that code_, but not what it calls. Calling gp_function from inside
there switches to the new global scope and off it goes.

Normally, I'd recommend your second option, passing a as an argument.
It's flexible, clear, doesn't rely on fancy names and hidden state.
But to answer your actual question: Yes, there is another way to do
it. In all probability, gp_function is actually defined at module
scope (I'm guessing here but it seems likely based on your
description). Simply assign to the module's namespace before calling
it - it'll "see" that as a global.

ChrisA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top