繁体   English   中英

在由 IPython 内核提供支持的 Jupyter notebook 中重置下划线 (`_`) 变量

[英]Reset underscore (`_`) variable in Jupyter notebook powered by IPython kernel

编辑:该问题已在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 notebook 中运行相同的代码后,无论最新输出是什么, _将永远保持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]

获得上次执行结果的一种安全方法(绕过下划线的特殊用法)是:

from IPython import get_ipython

ipython = get_ipython()

_ = ipython.last_execution_result.result

如果最后一次执行没有结果,那么上面将设置 underscore 为None

因此,这不会(必然)获得具有 result 的上次执行的结果

当下划线的特殊含义还完整的时候,就是上次有结果的执行的结果(基本跳过None值)。

要获得这种行为需要更多的参与。

如果您的代码在全局上下文中执行(因此,不在库中),那么您可以执行以下操作:

_ = Out.get(max(Out.keys(), default=0))

当没有执行结果时,这会将下划线设置为None

如果您的代码在库中执行,并且您不想传入globals() ,那么您可以执行以下操作:

out_hist = ipython.history_manager.output_hist  # ipython as set above

... out_hist.get(max(out_hist.keys(), default=0)) ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM