Python exec 的变量范围?

Python variable scope for exec?

下面是 2 个代码片段。

我想复制 f1 的效果,其中外部变量 x 由内部函数 g 修改。

然而,不是定义一个内部函数g,而是通过executing/interpreting一个字符串获得g

代码:

def f1():
  x = []
  def g():
    x.append(1)
  g() 
  print x


def f2():
  x = []
  strr = "def g():\n  x.append(1)\n"
  exec(strr)
  locals()["g"]()
  print x

f1 中,我得到 [1] 作为打印输出,但在 f2 中,我得到 x undefined 错误。我想知道如何使变量 x 在字符串定义函数 g.

中可访问

跟进:

如果我想对 g 应用装饰器会怎样?假设我有一个 "timeout" 装饰器,如果 运行:

花费的时间太长,该装饰器就会失败
def f1():
  x = []
  @timeout(1)
  def g():
    x.append(1)
  g() 
  print x

编辑:我设法解决了如下问题,由于本地没有定义超时,我必须将超时的定义从全局移动到本地,照常进行。

def f2():
  x = []
  strr = "@timeout(1)\ndef g():\n  x.append(1)\n"
  locals()['timeout'] = globals()['timeout']
  exec strr in locals()
  locals()["g"]()
  print x

您需要为 exec 添加名称 space。使用本地名称 space (exec strr in locals()) 并且有效:

def f2():
    x = []
    strr = "def g():\n  x.append(1)\n"
    exec strr in locals()
    locals()["g"]()
    print x

>>> f2()
[1]