考虑以下代码:
aDict = {}
execfile('file.py',globals(),aDict)
aDict['func2']() # this calls func2 which in turn calls func1. But it fails
file.py包含以下内容:
def func1():
return 1
myVar = func1() # checking that func1 exists in the scope
func2 = lambda: func1()
这给出了一条错误消息“ NameError: global name 'func1' is not defined。”
我不确定这里发生了什么。file.py
中
的代码使用空的本地命名空间执行。
然后,在该代码中,定义了一个新函数,该函数立即被成功调用。这意味着该功能确实存在于该范围内。
那么...为什么func1
不能在 lambda 中调用?
在其他语言中,lambdas/closures 绑定到定义它们的范围。
Python中的规则是怎样的?它们是否绑定到范围?到命名空间?