Sub topic 12
iter() with a sentinel for read loops
This chapter assumes you know the iterator protocol (__iter__, __next__, StopIteration) and how a for loop uses it. You should also be comfortable with lambda and with reading from file objects.
The two-argument form of iter()
You usually call iter() with one argument, an iterable. It also accepts a second form: iter(callable, sentinel). The first argument must be a function that takes no arguments. The second is the sentinel, a value that marks the end of the data.
The resulting iterator calls the function on every next(). It returns each result, unless the result equals the sentinel. At that point it raises StopIteration and the sentinel is discarded.
import io
f = io.StringIO("abcdef")
for chunk in iter(lambda: f.read(2), ""):
print(chunk)This prints ab, cd and ef. When the stream is exhausted, f.read(2) returns an empty string. That equals the sentinel "", so the loop ends without yielding it.
Why it exists
Many read APIs have no iterator of their own. They signal the end with a special return value: read() returns "" or b"", and queue.get_nowait() is another case where you must check the result yourself. Without iter(), you write a loop like this:
import io
f = io.StringIO("abcdef")
while True:
chunk = f.read(2)
if chunk == "":
break
print(chunk)The sentinel form does the same job in two lines. It also gives you a real iterator, which you can pass to sum(), map() or itertools.islice().
Passing arguments with functools.partial
The callable takes no arguments, so you must bind them first. A lambda works. functools.partial is often cleaner for binary reads:
import io
from functools import partial
stream = io.BytesIO(b"hello world!")
total = 0
for block in iter(partial(stream.read, 4), b""):
total += len(block)
print(block)
print(total) # 12Here the sentinel is b"", not "", because binary reads return bytes. Matching the sentinel's type to the read mode is the most common mistake with this idiom.
How it works
Three details follow from this flow:
- The comparison uses
==, notis. A sentinel of0also matches0.0andFalse. - If the function itself raises
StopIteration, iteration also ends. - Nothing is read until the first
next(), so the loop is lazy like any other iterator.
Common errors
Passing a value that is not callable fails immediately:
try:
iter([1, 2, 3], 0)
except TypeError as e:
print(e) # iter(v, w): v must be callableOther mistakes are quieter:
- Writing
f.read(2)instead oflambda: f.read(2). This passes a string, not a function, so you get theTypeErrorabove. - Choosing a sentinel the function never returns. The loop never ends. Reading a file with
readline()ends on"", but a socket that returnsNoneon timeout will not matchb"". - Reusing the iterator. Once exhausted, it stays exhausted, even if more data later appears in the source.
When not to use it
A file object is already iterable, so for line in f: is better for line-by-line reading. Use the sentinel form when the unit is a fixed-size block, or when the source is a function with an end marker, such as iter(input, "quit") for a prompt that stops when the user types quit.
Exercise
A binary file is opened with open("data.bin", "rb"). Write the for statement that reads it in 1024-byte blocks using iter() with a sentinel. Which sentinel do you use, and why not ""?
Show answer
for block in iter(partial(f.read, 1024), b""): (with from functools import partial; lambda: f.read(1024) also works). The sentinel is b"" because a binary read returns bytes. At the end of the file, f.read(1024) returns b"", and b"" == "" is False in Python 3, so a "" sentinel would never match and the loop would never stop.