Sub topic 3
How the shell evaluates and echoes expressions
This chapter assumes you can write basic Python (variables, functions, loops, conditionals), can open a terminal, and have started the interactive shell with python3. It explains what the shell does between pressing Enter and seeing a result. Once you know that, you can predict when output appears and when it doesn't.
The read-eval-print loop
The interactive shell is a read-eval-print loop, often shortened to REPL. It repeats four steps:
- Read one complete statement from the prompt.
- Compile and run it.
- If the statement is an expression, pass its value to a display function.
- Show the next prompt.
The echo is not part of evaluation. Python runs your code the same way in the shell and in a script. The shell adds one extra step, which is displaying the value of an expression statement.
>>> 2 + 3
5
>>> _ * 10
50The first line is an expression, so the shell shows 5. The second line uses _, which holds the last echoed value. Chapter 5 covers _ in detail. Here it only shows that the echo step does more than print.
Expressions and statements
An expression produces a value: 2 + 3, len("abc"), name, [1, 2, 3]. A statement performs an action. Assignment, import, def, for, if, and del are all statements.
An expression used on its own line is called an expression statement. Only expression statements are echoed. A line such as x = 5 is an assignment statement, so it produces no output.
>>> x = 5
>>> x
5
>>> x + 1
6
>>> import math
>>> math.pi
3.141592653589793Assignments and imports print nothing, even though they succeeded. Typing the bare name x is an expression, and that is what prints.
| You type | Kind | Echo |
|---|---|---|
| `x = 5` | assignment statement | none |
| `x` | expression | `5` |
| `import math` | import statement | none |
| `math.sqrt(16)` | expression | `4.0` |
| `[].sort()` | expression whose value is `None` | none |
| `del x` | del statement | none |
What the echo step does
In Python 3, the shell compiles each input in "single" mode. In this mode, every expression statement at module level is passed to sys.displayhook. This is an ordinary function in the sys module. The default hook does three things:
- If the value is
None, it does nothing. - Otherwise it stores the value in
builtins._, which is why_works. - It writes
repr(value)followed by a newline to standard output.
The diagram follows below in the required format.
None is not echoed
Because the default hook skips None, many calls appear to do nothing. They do return a value, but it is None.
>>> result = print("hi")
hi
>>> result
>>> result is None
TrueThe text hi is output produced by print() while it ran. It is not an echo. The call's value was None, so nothing more appeared.
This explains a common surprise with methods that change an object in place:
>>> numbers = [3, 1, 2]
>>> numbers.sort()
>>> numbers
[1, 2, 3]numbers.sort() sorts the list and returns None, so the shell shows nothing. You have to type numbers to see the result. The same applies to append, extend, update, and reverse.
The reverse mistake is also common. Calling sorted(numbers) returns a new list, so it does echo, but the original list is unchanged.
>>> data = [3, 1, 2]
>>> sorted(data)
[1, 2, 3]
>>> data
[3, 1, 2]The echo shows repr, not the text
The hook writes repr(value). For many objects, repr is a form meant to be unambiguous for a programmer, often one you could paste back into Python. This is why strings show quotes and escape sequences:
>>> s = "hello\n"
>>> s
'hello\n'
>>> print(s)
hello
>>>print(s) writes the characters in the string, including the newline, and then its own newline. That leaves a blank line. The next chapter compares print() and repr in detail. For now, remember that an echoed string with quotes is not a different string. It is the same value displayed in a different form.
You can check the output of the echo yourself:
>>> repr("hi")
"'hi'"
>>> 0.1 + 0.2
0.30000000000000004
>>> [1, "a", None]
[1, 'a', None]
>>> print
<built-in function print>The last line shows a classic mistake. Typing print without parentheses names the function and doesn't call it. The shell echoes the function object and nothing is printed.
Several expressions in one input
The semicolon lets you put more than one statement on a line. In the shell, each expression statement is echoed:
>>> 1; 2; 3
1
2
3Expression statements inside a module-level block are echoed too. They are not collected into a single result:
>>> for i in range(3):
... i * 2
...
0
2
4In a script, the loop body i * 2 would compute values and discard them. Here it displays them, which is handy for quick experiments. This is only true at module level. Code inside a function body is compiled normally, so a bare expression there is never echoed:
>>> def f():
... 5
... return 1
...
>>> f()
1The line 5 inside f is evaluated and thrown away. Only the call f() at the prompt is an expression statement of the shell, and its value, 1, is echoed.
Assignment expressions and tuples
An assignment statement doesn't echo, but an assignment expression does. The walrus operator := is an expression, and at the top level of the shell it must be wrapped in parentheses:
>>> (y := 7)
7
>>> y
7Commas build tuples, so a line with commas is one expression:
>>> 1, 2
(1, 2)
>>> x = 1, 2
>>> x
(1, 2)Customizing the echo
Since the echo comes from sys.displayhook, you can replace it. This shows exactly how the mechanism works:
>>> import sys
>>> def hook(value):
... if value is not None:
... print("value:", repr(value))
...
>>> sys.displayhook = hook
>>> 2 + 3
value: 5
>>> "text"
value: 'text'
>>> sys.displayhook = sys.__displayhook__
>>> 2 + 3
5The custom hook doesn't update _, because only the default hook does that. The line sys.displayhook = sys.__displayhook__ restores the original. Replacing the hook affects only that session. Tools such as IPython and other shells use this same extension point to provide pretty-printed output.
Common errors
- Expecting
x = 5to display5. Assignment is a statement. Typexon the next line. - Reading a missing echo as a failure. A call that returns
Noneshows nothing, as withlist.sort()andprint(). - Writing
printinstead ofprint(...). You get<built-in function print>and no output. - Assuming echoed quotes are part of the string. They belong to the
reprdisplay, not the data. - Expecting echoes from a function body or from a script. The echo happens only for expression statements typed in the shell at module level, not for code in a function or run from a file with
python script.py. - Forgetting parentheses with
:=.y := 7at the prompt is a syntax error. Use(y := 7).
Checking what you got
When the echo is ambiguous, ask Python directly:
>>> value = "5"
>>> value
'5'
>>> type(value)
<class 'str'>
>>> value == 5
FalseThe echoed '5' has quotes, which tells you it is a string. type() confirms it. Compare this with the integer 5, which is echoed without quotes. Reading the echo carefully is often enough to tell the type of a value.
Exercise
You type names = ["b", "a"] and then names.sort(). The shell shows nothing after the second line. Why, and what do you type to see the sorted list?
Show answer
names.sort() sorts the list in place and returns None. The shell doesn't echo None, so nothing appears. Type names to see ['a', 'b'].
Exercise
What does the shell show for each of these lines, in order: n = 4, n * 2, "hi", print("hi")?
Show answer
The first line shows nothing, because assignment is a statement. The second shows 8. The third shows 'hi' with quotes, the repr. The fourth shows hi without quotes, written by print(). The value of that call is None, so nothing is echoed after it.
Exercise
Why does the code def f(): 5 followed by f() not display 5?
Show answer
The expression 5 is inside a function body, which is not echoed. The function returns None because it has no return statement, so the call f() has the value None, and None is not echoed either.