我在 Django 控制台中做了一些事情,我意识到在lambda
表达式中无法识别全局变量,例如,如果您在 python 中甚至在 iPython 控制台中执行以下代码,它可以完美运行:
a = 10
foo = lambda x: x + a
foo(10) # returns 20
但是如果你在 Django shell 中使用 iPython 执行它,它就不起作用:
In [8]: foo = lambda x: x + a
In [9]: a = 10
In [10]: foo(10)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 foo(10)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(x)
----> 1 foo = lambda x: x + a
NameError: global name 'a' is not defined
iPython 版本 0.13.2
先感谢您!
编辑
a
如果我在 lambda 函数之前分配事件,问题仍然存在:
In [1]: a = 10
In [2]: foo = lambda x: x + a
In [3]: foo(10)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <module>()
----> 1 foo(10)
/usr/local/lib/python2.7/dist-packages/django/core/management/commands/shell.pyc in <lambda>(x)
----> 1 foo = lambda x: x + a
NameError: global name 'a' is not defined
In [4]:
───────────