python - 在由 IPython 内核提供支持的 Jupyter 笔记本中重置下划线 (`_`) 变量
问题描述
编辑:该问题已在GitHub中报告。我将问题留在这里,以防它帮助其他人找到问题(我无法)。
在 Jupyter notebook 中工作时,为了方便起见,我经常使用该_
变量(它返回最新代码执行的输出)。但是,当_
用作未使用变量的占位符(Python 中的典型用例)时,它会破坏第一个用例。
请注意,这在 IPython 控制台中按预期工作。下面,_
在循环中用作未使用的占位符后,再次保存最新的返回值。
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 _
,那么_
将不再是可访问的变量。
简而言之,_
Python 中变量的两种用法在 Jupyter 笔记本中发生冲突,但在 IPython 控制台中没有。这只是一个不便,但我很想知道如何解决它 - 或者为什么会这样。
编辑:
$ 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
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 中运行此代码
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]
推荐阅读
- reactjs - 在 DataView 组件中使用 reactPrime 库如何更新动态值(react hook)?
- javascript - 阻止脚本多次加载
- reactjs - Azure B2C 重定向到自定义域
- azure - 是否可以复制一个任务的输出文件并从 Azure 管道中的下一个任务访问?
- c - 在我的生成文件中意外执行“所有”目标
- php - SQL 数据库上传中的 RUN API
- javascript - React table 在构建中给出空表
- ios - MapKit中聚类期间消失的标记
- ruby-on-rails - 对于 csv 文件的每一行,使用 ruby on rails 打印每一行的第 n 列
- .net - 仅当文件存在时,才在 PowerShell 中使用 WinSCP 从 SFTP 服务器的阵列下载文件