代码在函数外部完美执行,但在函数内部却不行

code executes perfectly outside of a function, but not inside

编辑: 这个问题上面的链接没有回答 mod 添加了。正如我之前在评论中所说,Python 3 带来了变化,而这些答案中给出的 examples 是针对 Python 2 的。如果我在我的 Python 3 环境中编译它们,我得到了与此处相同的错误。

考虑

str = "x = [113, 223]"
exec(str)
print(x[0]) #113

这非常有效。但是如果我想让这个代码在一个函数中执行,它returns 一个错误NameError: name 'x' is not defined。这是一个最小的工作示例:

def some_code():
    str = "x = [1, 2]"
    exec(str)
    print(x)

some_code()

这是怎么回事?

我需要

的解决方案

天真地将相关代码移动到一级范围解决了它。

string = "x = [113, 223]"
exec(string)

def some_code():
    print(x[0]) #113

另一种方法: 我开始更多地尝试 exec(),据我所知 exec() 写下了结果(在本例中 x) 到 locals()globals() 内置词典中。因此,下面是该问题的另一种解决方案,但似乎比较hacky:

def some_code():
    string = "x = [113, 223]"
    exec(string)
    print(locals()['x'][0]) #113

some_code()

以同样的方式,您可以定义自己的字典来代替 locals(),其中 exec() 存储 x,在我看来,这更清晰:

exec_results = {}

def some_code():
    string = "x = [113, 223]"
    exec(string, None, exec_results)
    print(exec_results['x'][0]) #113

some_code()

我强烈反对将 exec() 用于像这样非常简单的情况,但如果您希望将来使用它,我强烈建议您查看在此之前创建的关于同一主题的其他线程问题,例如 exec() 上的 running-exec-inside-function and globals and locals in python exec(). Check out the Python docs 以阅读有关 exec() 的更多信息。