首页 > 解决方案 > 在由 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

标签: pythonjupyter-notebookipython

解决方案


根据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]


推荐阅读