以下仅在使用ipython而不是使用python终端时发生
def function1(name):
return name
def function2(name):
return "hello "+function1(name)
它会产生以下错误:
全局名称'function1'未定义
我正在使用python 2.7并通过键入以下命令使用python调用IPython
from IPython import embed
embed()
使用jupyter notebook
时不会发生此问题答案 0 :(得分:1)
这似乎是一个持续存在的问题,已经修复,后来又重新出现。从本质上讲,无论你在shell中输入什么,都会被添加到locals()
,但这些函数在被调用时仍会检查globals()
。
https://github.com/ipython/ipython/issues/62
快速,hackey修复是使用:
globals().update(locals())
在嵌入式会话中。
假设我创建了一个文件test.py
:
from IPython import embed
print "hello, ipython"
embed()
现在,我这样做:
(py27) Juans-MacBook-Pro:~ juan$ python ip.py
hello, ipython
Python 2.7.13 |Anaconda 4.3.0 (x86_64)| (default, Dec 20 2016, 23:05:08)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: def function1(name):
...: return name
...:
...: def function2(name):
...: return "hello "+function1(name)
...:
In [2]: function2('Juan')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
/Users/juan/ip.py in <module>()
----> 1 function2('Juan')
/Users/juan/ip.py in function2(name)
3
4 def function2(name):
----> 5 return "hello "+function1(name)
NameError: global name 'function1' is not defined
怪异。但是真的!
在[3]中:globals() 出[3]: {&#39; builtins &#39;:, &#39; doc &#39;:无, &#39; 档案&#39;:&#39; ip.py&#39;, &#39; 名称&#39;:&#39; 主要&#39;, &#39; 包&#39;:无, &#39;嵌入&#39;:}
并注意:
In [4]: 'function1' in globals()
Out[4]: False
In [5]: 'function2' in globals()
Out[5]: False
但是,
In [7]: 'function1' in locals()
Out[7]: True
In [8]: 'function2' in locals()
Out[8]: True
所以,如果我这样做:
In [11]: globals().update(locals())
In [12]: function2('Juan')
Out[12]: 'hello Juan'