Kivi Kivit Kivi Kivit - 2 years ago 64
Python Question

How to use a function containing eval in a file by variable defined at another file from that another file?

Assume, I have created an python file ( name which contains many functions and other things. One of the function is this (of course, it is simplified):

def func(string):
assert eval(string)

Besides, I have created an python file which imports func() from the file mentioned above. Then this second python file try to execute following process:

from FirstFile import func
amk = 1
func("amk == 1")

When variable "amk" is in the first file, no problem reveals. However, when variable "amk" is in the second file, which is illustrated here, an error reveals:

NameError: name 'amk' is not defined

Would you like to please help me solve this problem?

Answer Source

by default eval executes in the current local/global scope, if you want to specify a different environment you can do something like:

eval("x == 1", {"x":1})

so your function could take an optional environ argument:

def func(string, environ=None):
    assert eval(string, environ)

then you can call the function from the other module passing locals() as the environment:

from FirstFile import func
amk = 1
func("amk == 1", locals())

As a side note I'd recommend against evaluating arbitrary code especially if it is coming from another source / module as it could accidentally contain harmful code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download