【问题标题】:External variables in lambda functions in PythonPython 中 lambda 函数中的外部变量
【发布时间】:2013-08-10 02:47:47
【问题描述】:

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]

【问题讨论】:

  • 第一个块中的代码在 python2.7 和 python3.3 上都适用于我。所以我不确定你的实际问题是什么
  • @inspectorG4dget 我更新了 OP
  • @user815423426 您的代码在 py2.x,3,x 和 ipy2.x, 3.x 中运行良好。但是,django 的 shell(ipy 2.7) 引发了同样的错误。奇怪!

标签: python django lambda ipython


【解决方案1】:

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

这是金字塔 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

【讨论】:

  • 谢谢!很高兴知道这一点。我上面描述的行为在 IPython v1.0 中偶尔发生。您在 1.0 中注意到这一点了吗?
猜你喜欢
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多