Sub topic 5
Reusing the last result with _
This chapter assumes you can start the shell and type expressions at the >>> prompt. It also assumes you know that the shell echoes the value of an expression. Here you will learn how the shell keeps that value in _, when _ changes, and how to avoid breaking it.
What _ holds
When you enter an expression, the shell prints its value and also stores it in a variable named _. The next line can use it.
>>> 2 + 3
5
>>> _ * 10
50
>>> _ + 1
51Each echoed result replaces the previous one. After _ * 10 runs, _ is 50, not 5. This helps when you run a calculation and realize you want to keep working with the answer without retyping it.
The storing is done by sys.displayhook, the function the shell calls to display each expression result. The hook writes the value to builtins._. That is why _ works in every module of the session, not only in your own code.
When _ changes and when it does not
Only an expression whose value is not None updates _. Several common actions leave it alone:
- Assignments such as
x = 10are statements, not expressions, so nothing is echoed or stored. - A call to
print()returnsNone, which the shell does not echo or store. - A line that raises an exception produces no value.
>>> 7 * 6
42
>>> x = 10
>>> print("hi")
hi
>>> int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> _
42After four more lines, _ still holds 42. The flowchart shows the decision the shell makes for each line you enter.
Using _ with results you did not name
A typical use is a call whose result you forgot to save.
>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> round(_, 3)
1.414
>>> type(_)
<class 'float'>If you need a value for more than a line or two, give it a name: root = _. The next expression overwrites _, so the value is easy to lose.
The shadowing gotcha
_ is a builtin that the shell sets. If you assign to _ yourself, you create a global variable with the same name. Python finds your global first, so the shell's value is hidden. The shell keeps storing results in builtins._, but you no longer see them.
>>> _ = "mine"
>>> 2 + 3
5
>>> _
'mine'
>>> del _
>>> 2 + 3
5
>>> _
5Running del _ removes your global and brings back the builtin. People hit this by using _ as a throwaway name in loops, such as for _ in range(3):. That is normal in scripts, but in the shell it shadows the last result until you delete it.
Another reason to avoid _ as your own name is that some libraries use _ as an alias for a translation function. Checking for this mixing is easy: if _ has a value you did not expect, look for an earlier assignment.
Limits
_exists only in the interactive shell. A script run withpython script.pynever sets it, so code that relies on it fails with aNameError.- Only one value is kept. Use named variables for anything you need again.
- Some other interactive environments, such as IPython, add their own history variables (
__,___). The plain Python shell does not.
Exercise
Exercise
You type len("python") and the shell prints 6. You then type label = "n" and print(label), which prints n. What does _ hold now, and what would _ * 2 print?
Show answer
_ still holds 6. The assignment is a statement, and print() returns None, so neither updates _. The expression _ * 2 prints 12.
Exercise
In a fresh session you run _ = 0, then 3 + 4, then _. The shell prints 0 for the last line. Why, and how do you fix it?
Show answer
The assignment created a global _ that hides the builtin _ the shell uses to store results. Run del _ to remove the global. After the next expression, _ holds that expression's result again.