lambda中的外部变量在Python中起作用

时间:2013-08-10 02:47:48

标签: python django lambda ipython

受到this answer中的构造的启发,我正在尝试执行以下操作:

values = range(3)
vector = np.random.randint(3, size=(5,))
f = lambda x: x in values
result = [f(a) for a in values]

但我得到global name 'values' is not defined

如果我尝试上面链接的解决方案,即:

,我会得到同样的错误
A = [[0,1,2], [1,2,3], [2,3,4]]
v = [1,2]
B = [map(lambda val: val in v) for a in A]

自该解决方案发布以来,Python是否发生了变化? (我正在使用 2.7.4 )。如果是这样,我如何在lambda函数中访问外部变量?我应该宣布它是全球性的吗?把它作为另一个输入传递?

更新1:

我只是在 IPython (1.0)中的嵌入式shell 中注意到这个问题。

更新2:

GitHub上有关于该主题的IPython ticket,但目前还不清楚问题是否已经解决。

更新3(不是来自OP):

错误可以在django的shell中重现(感谢@Ashwini)

$ ./manage.py shell
Python 2.7.4 (default, Apr 19 2013, 18:32:33) 
Type "copyright", "credits" or "license" for more information.

IPython 0.13.2 -- An enhanced Interactive Python.

In [1]: import numpy as np
In [2]: values = range(3)
In [3]: vector = np.random.randint(3, size=(5,))
In [4]: f = lambda x: x in values
In [5]: result = [f(a) for a in values]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 result = [f(a) for a in values]
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(x)
----> 1 f = lambda x: x in values

NameError: global name 'values' is not defined
In [6]: values
Out[6]: [0, 1, 2]

1 个答案:

答案 0 :(得分:1)

我知道你的例子和bug报告中的代码在金字塔框架的交互式shell中成功运行(pshell,使用ipython 0.12!),但我记得以前遇到过这个问题。关键是,使用ipython&gt; = 0.11,它使用不同的代码。据我所知,0.10代码仍会有这个错误。

这是金字塔pshell.py

的简化摘录
def make_ipython_v0_11_shell():
    try:
        from IPython.frontend.terminal.embed import (
            InteractiveShellEmbed)
        IPShellFactory = InteractiveShellEmbed
    except ImportError:
        return None

    def shell(env, help):
        IPShell = IPShellFactory(banner2=help + '\n', user_ns=env)
        IPShell()

   return shell

def make_ipython_v0_10_shell():
    try:
        from IPython.Shell import IPShellEmbed
        IPShellFactory = IPShellEmbed
    except ImportError:
        return None

    def shell(env, help):
        IPShell = IPShellFactory(argv=[], user_ns=env)
        IPShell.set_banner(IPShell.IP.BANNER + '\n' + help + '\n')
        IPShell()

    return shell