How to use a function containing eval in a file by

2019-07-28 03:33发布

问题:

Assume, I have created an python file (FirstFile.py) 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?

回答1:

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.