Sub topic 11
Reading input in chunks with the walrus operator
This chapter assumes you can write a basic while loop and know that Python treats some values as false (0, "", None, empty collections). It also assumes you know how while True and break work, and that you have used input() or file.read(). You need Python 3.8 or newer.
The read-then-test problem
Many loops follow one pattern: get a value, check whether there is more data, process the value, and repeat. The test depends on the value you just read. A plain while loop has no place to read the value before the first test, so you have two common workarounds.
The first is to read once before the loop and again at the end of the body:
import io
stream = io.StringIO("abcdefgh")
chunk = stream.read(3)
while chunk:
print(chunk)
chunk = stream.read(3)This works, but the stream.read(3) call is written twice. If you change the chunk size in one place and forget the other, the program breaks quietly.
The second is while True with an early break:
import io
stream = io.StringIO("abcdefgh")
while True:
chunk = stream.read(3)
if not chunk:
break
print(chunk)The read appears once, but the real stopping rule is now inside the body, not in the loop header. A reader has to scan the body to learn when the loop ends.
The assignment expression, called the walrus operator because := looks like a pair of eyes and tusks, removes both problems.
What the walrus operator does
An assignment expression has the form name := expression. It evaluates the expression, binds the result to name, and produces that same value as its own result. An ordinary assignment statement (name = value) produces no value, so it cannot sit inside a condition. := can.
import io
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3):
print(chunk)The output is:
abc
def
ghEach time Python checks the loop condition, it does three things in order:
- It calls
stream.read(3). - It stores the result in
chunk. - It tests the result for truthiness.
If the result is truthy, the body runs, and chunk already holds the data. If it is falsy, the loop ends. This design depends on how Python evaluates a loop condition: the condition is re-evaluated before every pass, so the read happens before every pass too.
Why truthiness is the stopping signal
The loop above ends because read() returns an empty string at the end of the stream, and an empty string is falsy. Many reading APIs follow the same convention:
| Call | Value at end of data | Falsy? |
|---|---|---|
| `text_file.read(n)` | `""` | Yes |
| `binary_file.read(n)` | `b""` | Yes |
| `text_file.readline()` | `""` | Yes |
| `queue.get_nowait()` | raises `queue.Empty` | Not applicable |
| `input()` | raises `EOFError` | Not applicable |
The last two rows matter. The walrus pattern only works when the end of data is signaled by a falsy return value. If the function raises an exception instead, you need a try/except around the loop, and the walrus operator does not help.
A blank line in a file is not the same as the end of the file. readline() returns "\n" for a blank line, which is a non-empty and therefore truthy string. Only a real end of file produces "":
import io
lines = io.StringIO("alpha\nbeta\n\ngamma\n")
while line := lines.readline():
print(repr(line))The output is:
'alpha\n'
'beta\n'
'\n'
'gamma\n'The loop prints the blank line and keeps going. It stops only after 'gamma\n'.
Processing binary data in blocks
Reading in fixed-size blocks keeps memory use constant, no matter how large the input is. This is the most common real use of the pattern. The example below hashes a stream without loading all of it at once. It uses io.BytesIO so that it runs without any file on disk. With a real file, you would open it with open(path, "rb") and use the same loop.
import hashlib
import io
data = io.BytesIO(b"hello world" * 1000)
digest = hashlib.sha256()
total = 0
while block := data.read(4096):
digest.update(block)
total += len(block)
print(total)
print(digest.hexdigest())The first line printed is 11000. The second is the 64-character hexadecimal hash. The last block is only 2712 bytes long, which is fine: any non-empty block is truthy, however short.
Equivalence with while True and break
A walrus loop is a compact form of the while True version. These two loops behave identically:
import io
# Form 1: assignment expression in the condition
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3):
print(chunk)
# Form 2: while True with break
stream = io.StringIO("abcdefgh")
while True:
chunk = stream.read(3)
if not chunk:
break
print(chunk)Prefer the walrus form when the stopping rule is a simple test on the value you just read. Prefer while True when the body has several different exit points, or when you need work between the read and the test, such as logging or retry handling. The walrus form puts one rule in the header. It cannot hold several.
Combining the walrus with other conditions
You can add more tests to the condition with and and or. Put parentheses around the assignment expression, so that the grouping is explicit:
import io
lines = io.StringIO("one\ntwo\nquit\nthree\n")
while (line := lines.readline()) and line.strip() != "quit":
print("got", line.strip())The output is got one and got two. The loop stops at the quit line. Because and short-circuits, the second test runs only when line is non-empty.
Using continue safely
Earlier in this tutorial you saw that continue can cause an infinite loop when the state update sits at the bottom of the body. The walrus pattern avoids that bug. The update, which is the read, happens in the condition, and continue jumps back to the condition. The loop therefore always advances:
import io
lines = io.StringIO("# comment\nx=1\n\n# another\ny=2\n")
while line := lines.readline():
line = line.strip()
if not line or line.startswith("#"):
continue
print(line)The output is x=1 and y=2. Comments and blank lines are skipped, and the loop still reaches the end of the input.
Gotchas
Precedence: the comparison swallows the value
The := operator has very low precedence. In chunk := stream.read(3) != "", Python evaluates the comparison first. It then assigns the resulting True or False to chunk:
import io
stream = io.StringIO("abcdefgh")
while chunk := stream.read(3) != "":
print(chunk)This prints True three times, not the data. The loop still ends, but chunk holds a boolean, not the text. Parenthesize the assignment when you combine it with a comparison:
import io
stream = io.StringIO("abcdefgh")
while (chunk := stream.read(3)) != "":
print(chunk)Now chunk holds the text, and the output is abc, def, gh.
You cannot use plain = in a condition
while chunk = stream.read(3): is a SyntaxError. Python rejects it on purpose, so that a typo for == cannot silently become an assignment, as it can in some other languages.
The variable outlives the loop
A name bound with := in a while condition belongs to the enclosing scope. After the loop, chunk still exists, and it holds the last value tested, which is the falsy value that ended the loop. Do not reuse the name later for something unrelated without reassigning it.
Falsy does not always mean finished
Truthiness is the right test only when every valid item is truthy. If valid data can be 0, "", or [], a bare truthiness test ends the loop too early. In that case, test against a sentinel explicitly:
tokens = iter([0, 1, "", 2])
while (token := next(tokens, None)) is not None:
print(repr(token))The output is 0, 1, '', 2. All four values are falsy or truthy as the data happens to be, and the loop ends only when next returns the None default.
Do not use it when a for loop already fits
If the source is already iterable, a for loop is clearer. Files iterate over lines directly:
with open("data.txt") as f:
for line in f:
print(line.rstrip())For a repeated call with a sentinel, such as chunked reads, the built-in iter(callable, sentinel) gives a for loop form. It calls the function with no arguments until the function returns the sentinel:
import io
stream = io.StringIO("abcdefgh")
for chunk in iter(lambda: stream.read(3), ""):
print(chunk)Both forms are acceptable. The iter form has an advantage: its sentinel test is an equality check against an explicit value, so it does not rely on truthiness. The walrus form is usually easier to read for people who have not seen the two-argument iter.
Choosing a form
| Situation | Best fit |
|---|---|
| Read blocks until an empty value, one simple rule | `while chunk := f.read(n):` |
| Valid items can be falsy | `while (x := get()) is not None:` |
| Source is already iterable | `for item in source:` |
| Repeated call with an explicit end marker | `for x in iter(func, sentinel):` |
| Several exit conditions, or work between read and test | `while True:` with `break` |
| Source raises an exception at the end | `while True:` inside `try`/`except` |
Summary
An assignment expression in a while condition reads a value, names it, and tests it in one step. This removes the duplicated read from the read-then-test pattern and keeps the stopping rule in the loop header. It relies on the end of data being falsy, so check how the API you call signals the end. Parenthesize the assignment when you add comparisons, and use an explicit is not None test when valid values can be falsy.
Exercise
The loop below is meant to print each chunk of the stream, but it prints True three times instead. Explain why, and write the corrected condition. import io stream = io.StringIO("abcdefgh") while chunk := stream.read(3) != "": print(chunk)
Show answer
The operator := has lower precedence than !=, so Python first evaluates stream.read(3) != "", which gives True or False, and assigns that boolean to chunk. The loop prints True for "abc", "def", and "gh", then stops when read returns "" and the comparison is False. The fix is to parenthesize the assignment: while (chunk := stream.read(3)) != "":. A simpler fix is while chunk := stream.read(3):, which relies on the empty string being falsy.
Exercise
Write a loop that uses the walrus operator to read a BytesIO object named data in blocks of 5 bytes and collects the length of every block in a list called sizes. For data = io.BytesIO(b"abcdefghijklm") what should sizes be?
Show answer
sizes = [] while block := data.read(5): sizes.append(len(block)) The stream holds 13 bytes, so the blocks are 5, 5, and 3 bytes long, and sizes is [5, 5, 3]. The next read returns b"", which is falsy, so the loop ends.
Exercise
A list of readings is iterated with next(readings, None) inside while (r := next(readings, None)):. The readings are 3, 0, 5. How many values does the loop process, and how do you fix it?
Show answer
It processes only one value, 3. The second reading, 0, is falsy, so the loop ends before processing 0 and 5. Fix it by testing against the sentinel explicitly: while (r := next(readings, None)) is not None:. Then all three values (3, 0, 5) are processed, and the loop ends only when next returns the default None.