Python: 如何让eval() 看到局部变量?

Python: How to let eval() see local variables?

我有以下内容:

x = [1,2,3,4,5]
def foo(lbd:str, value):
    ret_val = eval(lbd, globals(), locals())
    print(ret_val)

在此调用中使用 'value' 变量成功:

>>> foo("[i for i in value]",x)
            
[1, 2, 3, 4, 5]

但是这个失败了:

>>> 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: name 'value' is not defined

我可以解决这个问题,但很想知道这里发生了什么。

>>> foo(r"(lambda V=value: any([x in V for x in {'',0,None,'0'}]) )()", x)
False

这是一个非常微妙的观点。所以,如果你阅读 documentation for eval, it doesn't mention the case where you provide arguments for both globals and locals, but I am fairly certain it works the same as for exec:

If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.

在 class 定义中,函数无法访问其封闭范围。所以这 与错误 完全相同:

>>> class Foo:
...     value = [1,2,3]
...     print([x in value for x in [2,4,6]])
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in Foo
  File "<stdin>", line 3, in <listcomp>
NameError: name 'value' is not defined

因为列表理解通过在幕后创建一个函数对象来工作。这也是为什么您需要 self.some_method 来访问 class 中定义的其他方法的名称。 the excellent accepted answer here.

中有关上述内容的更多信息

所以它与:

相同
>>> def foo():
...     x = 3
...     return eval('(lambda: x + 1)()', globals(), locals())
...
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <lambda>
NameError: name 'x' is not defined

然而,这工作得很好:

>>> def foo():
...     x = 3
...     return eval('x + 1', globals(), locals())
...
>>> foo()
4

因为不涉及(非)封闭函数作用域。

最后,以下是有效的原因:

>>> def foo():
...     values = [1,2,3]
...     return eval('[x+2 for x in values]', globals(), locals())
...
>>> foo()
[3, 4, 5]

是因为推导的最左边 for 子句中的可迭代对象不是在推导的函数范围内而是在推导发生的范围内求值(它实际上是作为参数传递的)。你可以在列表推导的反汇编中看到这一点:

>>> import dis
>>> dis.dis('[x+2 for x in values]')
  1           0 LOAD_CONST               0 (<code object <listcomp> at 0x7fe28baee3a0, file "<dis>", line 1>)
              2 LOAD_CONST               1 ('<listcomp>')
              4 MAKE_FUNCTION            0
              6 LOAD_NAME                0 (values)
              8 GET_ITER
             10 CALL_FUNCTION            1
             12 RETURN_VALUE

Disassembly of <code object <listcomp> at 0x7fe28baee3a0, file "<dis>", line 1>:
  1           0 BUILD_LIST               0
              2 LOAD_FAST                0 (.0)
        >>    4 FOR_ITER                12 (to 18)
              6 STORE_FAST               1 (x)
              8 LOAD_FAST                1 (x)
             10 LOAD_CONST               0 (2)
             12 BINARY_ADD
             14 LIST_APPEND              2
             16 JUMP_ABSOLUTE            4
        >>   18 RETURN_VALUE

注意,values 被求值,iter 被调用,结果被传递给函数:

              6 LOAD_NAME                0 (values)
              8 GET_ITER
             10 CALL_FUNCTION            1

“函数”基本上只是一个带追加的循环,请参阅:Disassembly of <code object <listcomp> at 0x7fe28baee3a0, file "<dis>", line 1> 了解列表推导式如何工作。

除了@juanpa.arrivillaga的, there is some discussion of this behavior in this bug report(这不是错误)。

这里有一个快速解决您的直接问题的方法:

x = [1,2,3,4,5]
def foo(lbd:str, value):
    ret_val = eval(lbd, {'value': value})
    print(ret_val)

>>> foo(r"any([x in value for x in {'',0,None,'0'}])", x)
False