Issue
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).
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.
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'
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.
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.
Edit:
$ python --version
Python 3.6.3 :: Anaconda, Inc.
$ ipython --version
6.5.0
$ jupyter notebook --version
5.6.0
Solution
Another way is the following:
import builtins
del builtins._
del _
del __
del ___
Just ignore any possible errors. In particular, if you get NameError: name '_' is not defined
, you must continue deleting __
etc.
After doing this, it will continue working from the subsequent cell (i.e. this method won't help getting the previous Out[n]
)
Explanation: in the piece of the code quoted by the other answer (source),
- the code checks if the value of
_
,__
,___
(note thatrange(1, 4)
excludes4
! So assigning____
is useless) is either undefined or the same object as the last 3Out[n]:
values. - if it is, then everything is updated.
- otherwise, nothing is updated.
Thus, if all of _
, __
, and ___
are undefined, then starting from the next cell, the output will be assigned to _
.
Importantly, if any one of these are incorrect, it will not work.
The del builtins._
is necessary because otherwise if the user or some library previously did something like
import gettext
gettext.NullTranslations().install()
then builtins._
will be overwritten, and it is necessary to delete it.
Answered By - user202729
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.