当我尝试运行使用runpy模块加载的文件中定义的方法时,出现意外的行为。这些方法看不到在该方法外定义的任何变量(包括导入的模块)。这里是我正在做它:闭包如何在runpy中工作?
#test.py
import runpy
env = runpy.run_path('test', {'y':'world'})
env['fn']()
〜
#test
import re
print(re.compile(r'^hello', re.IGNORECASE).sub('', "hello world"))
x = "hello"
print(x)
print(y)
def fn():
try:
print(re.compile(r'^hello', re.IGNORECASE).sub('', "hello world"))
except:
print("No re")
try:
print(x)
except:
print("No x")
try:
print(y)
except:
print("No y")
我预计test.py的输出为:
world
hello
world
world
hello
world
因为FN将构成重新封闭,X和y。
但是,相反,我得到:
world
hello
world
No re
None
None
看起来再没有即使它应该是正常的闭合行为FN内定义。 x和y更加陌生,因为它们看起来是被定义的,但被设置为None。
为什么会这样以及闭包如何与runpy一起工作?我如何实现正常行为,使fn能够“看到”外部变量?