python 3中exec函数的奇怪行为

svl*_*yso 6 python

为什么这段代码不起作用?

class wrapper(dict):
    pass

script = """
def foo():
    print(10)

foo()
"""
exec(script, wrapper())
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到了这条消息:

File "test.py", line 29, in <module>
exec(script, wrapper())
 File "<string>", line 5, in <module>
 File "<string>", line 3, in foo
KeyError: 'print'
Run Code Online (Sandbox Code Playgroud)

如果我将最后一行更改为

exec(script, {})
Run Code Online (Sandbox Code Playgroud)

然后一切正常。

我不明白,为什么完全透明的字典继承会改变脚本行为?

Diw*_*RMA -1

请使用 python 3.7 ------你的代码对我来说工作正常