此代码工作正常 - 它定义do_return
为全局,它定义do_proxy
为全局,并且可以在调用时do_proxy
解析。do_return
g1 = {}
exec("def do_return(): return 1", g1)
exec("def do_proxy(): return do_return()", g1)
merged = {**g1}
merged.pop("__builtins__")
print(merged.keys())
exec("print(do_proxy())", merged)
$ python3 main.py
dict_keys(['do_return', 'do_proxy'])
1
此代码不会:
g1 = {}
g2 = {}
exec("def do_return(): return 1", g1)
exec("def do_proxy(): return do_return()", g2)
merged = {**g1, **g2}
merged.pop("__builtins__")
print(merged.keys())
exec("print(do_proxy())", merged)
它抱怨do_return
没有定义,即使有一个全局命名do_return
:
$ python3 main.py
dict_keys(['do_return', 'do_proxy'])
Traceback (most recent call last):
File "main.py", line 8, in <module>
exec("print(do_proxy())", merged)
File "<string>", line 1, in <module>
File "<string>", line 1, in do_proxy
NameError: name 'do_return' is not defined
有没有办法合并来自多个调用的依赖全局变量,这些调用exec
在最初被调用时不共享相同的全局字典?
如果我global do_return
在内部调用也会发生同样的情况do_proxy
(尽管如果需要,我也希望第一个示例失败,同样需要它)。