Sub topic 11
Reading input in chunks with the walrus operator
This chapter assumes you can write a basic while loop, know that empty strings and 0 are falsy, and have used break inside while True. It also assumes Python 3.8 or newer, because the walrus operator does not exist in earlier versions.
The problem: read, test, repeat
Reading data in pieces has an awkward shape. You must read before you can test, and you must read again at the end of each pass. The classic version repeats the read call:
import io
stream = io.StringIO("abcdefgh")
chunk = stream.read(3)
while chunk:
print(chunk)
chunk = stream.read(3)The two stream.read(3) lines must stay identical. If you change the chunk size in one place and forget the other, the loop quietly misbehaves.
The usual fix is while True with break:
import io
stream = io.StringIO("abcdefgh")
while True:
chunk = stream.read(3)
if not chunk:
break
print(chunk)This works, but the real stopping condition is hidden inside the body instead of sitting in the loop header.
The walrus operator
The walrus operator := is an assignment expression. It assigns a value to a name and also gives back that value, so you can use it inside a larger expression such as a loop condition. It is called the walrus because := looks like a sideways walrus face.
import io
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3):
print(chunk)This prints abc, def, and gh. Before each pass, Python does three things:
- It calls
stream.read(3). - It stores the result in
chunk. - It tests that result for truthiness.
When the stream is exhausted, read returns an empty string, which is falsy, and the loop ends. The name chunk is an ordinary variable, so it is still available inside the body and after the loop.
Testing something other than truthiness
A bare walrus condition stops on any falsy value. That is wrong when a legitimate value can be falsy. In the next example the number 0 is real data, so a plain truthiness test would stop early. Compare the value against a sentinel with is not None instead:
values = iter([3, 0, 5])
while (value := next(values, None)) is not None:
print(value)This prints 3, 0, and 5. The call next(values, None) returns None when the iterator runs out, and only that value ends the loop.
The parentheses around the walrus expression matter here. They make the assignment happen first, and the comparison then runs on the assigned value.
Common errors
Missing parentheses before a comparison
The walrus operator has very low precedence, so without parentheses it captures the whole comparison:
import io
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3) != "":
print(chunk)This does not assign the text to chunk. It evaluates stream.read(3) != "" first and assigns that result, a boolean. The loop prints True three times, and the data is lost. Write while (chunk := stream.read(3)) != "": instead.
Falsy data that is valid
If a read can return 0, "", or an empty list as meaningful data, a bare while x := ... ends the loop too soon. Use an explicit sentinel test as shown above.
Using it where plain assignment is clearer
A walrus loop earns its place when the value is both fetched and tested on every pass. If you only need to assign a variable, use =. Python also forbids a bare walrus statement such as chunk := 5 on its own line. It must be part of an expression, or wrapped in parentheses.
Running on an older Python
On Python 3.7 or earlier, := is a SyntaxError. Check your version with python --version before using it.
Summary of when to use it
| Situation | Suggested form |
|---|---|
| Read until an empty result | `while chunk := read():` |
| Falsy values are valid data | `while (x := get()) is not None:` |
| Several steps before you can decide to stop | `while True:` with `break` |
| Fixed number of repeats | A `for` loop |
Exercise
This loop should print each line of text, including blank lines, and stop at the end. It stops at the first blank line instead. Why, and how do you fix it? import io stream = io.StringIO("one\n\ntwo\n") while line := stream.readline().strip(): print(line)
Show answer
The .strip() call turns a blank line ("\n") into an empty string, which is falsy, so the loop ends at the first blank line. Test the raw line for end of input instead. readline() returns "" only at the end of the stream, because a blank line is still "\n". Fix: while (line := stream.readline()) != "": followed by print(line.strip()) in the body.
Exercise
Rewrite this loop using a walrus operator in the condition, keeping the behavior the same. import io stream = io.StringIO("abcdefghij") while True: chunk = stream.read(4) if not chunk: break print(len(chunk))
Show answer
Use while chunk := stream.read(4): and keep print(len(chunk)) as the body. The output is 4, 4, 2 in both versions.