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

流过昼夜 提交于 2019-12-10 23:01:22

问题


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.



来源:https://stackoverflow.com/questions/37534046/how-to-use-a-function-containing-eval-in-a-file-by-variable-defined-at-another-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!