Python: Access from within a lambda a name that's in the scope but not in the namespace

那年仲夏 提交于 2019-12-13 05:43:16

问题


Consider the following code:

aDict = {}    
execfile('file.py',globals(),aDict)
aDict['func2']() # this calls func2 which in turn calls func1. But it fails

And file.py contains this:

def func1():
    return 1

myVar = func1() # checking that func1 exists in the scope

func2 = lambda: func1()

This gives an error saying "NameError: global name 'func1' is not defined."

I'm not sure what is happening here.
The code in file.py is executed with an empty local namespace.
Then, inside that code, a new function is defined, which is succesfully called right away. That means the function does exist in that scope.

So... why func1 cannot be called inside the lambda?

On other languages, lambdas/closures are bound to the scope in which they are defined.
How are the rules in Python? Are they bound to the scope? to the namespace?


回答1:


I think the namespace that func1 is defined in (the namespace of file.py) is gone, so it can't look it up again. Here is code where func1 is remembered, though it is ugly:

func2 = (lambda x: lambda : x())(func1)


来源:https://stackoverflow.com/questions/26939725/python-access-from-within-a-lambda-a-name-thats-in-the-scope-but-not-in-the-na

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!