Python:从Lambda内部访问一个在范围内但不在名称空间中的名称 [英] Python: Access from within a lambda a name that's in the scope but not in the namespace

查看:109
本文介绍了Python:从Lambda内部访问一个在范围内但不在名称空间中的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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:未定义全局名称'func1'."

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

我不确定这里发生了什么.
file.py 中的代码是使用空的本地名称空间执行的.
然后,在该代码内定义了一个新函数,该函数立即被成功调用.这意味着该功能确实存在于该范围内.

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.

那么...为什么不能在lambda内部调用func1?

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

在其他语言上,lambda/closures绑定到它们定义的范围.
Python中的规则如何?它们受范围限制了吗?到名称空间?

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?

推荐答案

我认为func1定义的名称空间(file.py的名称空间)已经消失,因此无法再次查找. 这是代码,虽然很难看,但仍能记住func1:

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)

这篇关于Python:从Lambda内部访问一个在范围内但不在名称空间中的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆