我有以下几点:
x = [1,2,3,4,5]
def foo(lbd:str, value):
ret_val = eval(lbd, globals(), locals())
print(ret_val)
Run Code Online (Sandbox Code Playgroud)
在此调用中使用 'value' 变量成功:
>>> foo("[i for i in value]",x)
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
但是这个失败了:
>>> foo(r"any([x in value for x in {'',0,None,'0'}])", x)
Traceback (most recent call last):
File "<pyshell#171>", line 1, in <module>
foo(r"any([x in value for x in {'',0,None,'0'}])", x)
File "<pyshell#165>", line 2, in foo
ret_val = eval(lbd, globals(), locals())
File "<string>", line 1, in <module>
File "<string>", line 1, in <listcomp>
NameError: …Run Code Online (Sandbox Code Playgroud)