在由IPython内核提供支持的Jupyter笔记本中重置下划线(`_`)变量 [英] Reset underscore (`_`) variable in Jupyter notebook powered by IPython kernel
问题描述
编辑:已在 GitHub .我将问题留在这里,以防其他人发现问题(我无法).
Edit: The issue has been reported in GitHub. I'm leaving the question here in case it helps other people find the issue (I was not able to).
在Jupyter笔记本中工作时,为了方便起见,我经常使用_
变量(它返回最新代码执行的输出).但是,当_
用作未使用变量的占位符(Python中的典型用例)时,它将破坏第一个用例.
I often use the _
variable for convenience when working in a Jupyter notebook (it returns the output of the latest code execution). However, when _
is used to as a placeholder for an unused variable (a typical use case in Python), it breaks the first use case.
请注意,这在IPython控制台中可以正常工作.在下面,_
在用作循环中的未使用占位符后再次保留了最新的返回值.
Note that this works as expected in an IPython console. Below, _
again holds the latest returned value after being used as an unused placeholder in the loop.
In [1]: 'value'
Out[1]: 'value'
In [2]: _
Out[2]: 'value'
In [3]: for _ in range(2):
...: print('hello')
...:
hello
hello
In [4]: _
Out[4]: 1
In [5]: 'value'
Out[5]: 'value'
In [6]: _
Out[6]: 'value'
但是,在Jupyter笔记本中运行相同的代码后,无论最新输出是什么,_
都将永久保留1
(循环中的最后一个值).如果我尝试del _
,则_
将不再是可访问的变量.
However, after running the same code in a Jupyter notebook, _
will forever hold 1
(the last value from the loop), no matter what the latest output is. If I try to del _
, then _
will no longer be an accessible variable.
简而言之,Python中_
变量的两种用法在Jupyter笔记本中发生冲突,但在IPython控制台中不是.这只是一个不便,但我很想知道如何解决它-或为什么会这样.
In short, the two uses of the _
variable in Python clash in a Jupyter notebook, but not in an IPython console. It's only an inconvenience, but I would be curious to know how to solve it - or why it is.
修改:
$ python --version
Python 3.6.3 :: Anaconda, Inc.
$ ipython --version
6.5.0
$ jupyter notebook --version
5.6.0
推荐答案
根据IPython源代码进行 ../lib/site-packages/IPython/core/displayhook.py 197 update_user_ns
Accooding to IPython source code ../lib/site-packages/IPython/core/displayhook.py 197 update_user_ns
update_unders = True
for unders in ['_'*i for i in range(1,4)]:
if not unders in self.shell.user_ns:
continue
if getattr(self, unders) is not self.shell.user_ns.get(unders):
update_unders = False
self.___ = self.__
self.__ = self._
self._ = result
要恢复下划线变量功能,只需在ipython repl中运行此代码
To recover underscore variable functionality,just run this code in ipython repl
out_len=len(Out)
for index,n in enumerate(Out):
if index==out_len-1: _=Out[n]
if index==out_len-2: __=Out[n]
if index==out_len-3: ___=Out[n]
if index==out_len-4:____=Out[n]
这篇关于在由IPython内核提供支持的Jupyter笔记本中重置下划线(`_`)变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!