Sub topic 12
iter() with a sentinel for read loops
This chapter covers the two-argument form iter(callable, sentinel). It turns "call this function until it returns a stop value" into an ordinary iterator. It assumes you know how iter() and next() work on iterables, what StopIteration does, and how to write a lambda or use functools.partial.
The problem: loops that end on a value
Some data sources are not collections. You can't iterate over them directly. You can only ask for the next piece by calling a function, and you know the data has ended when the function returns a special value. Reading a binary file in chunks is the classic case: read(n) returns b"" at end of file.
The usual loop looks like this:
import io
f = io.BytesIO(b"abcdef")
while True:
chunk = f.read(2)
if chunk == b"":
break
print(chunk)The while True plus break works, but the read, the stop test and the loop body are tangled together. The two-argument iter() separates them.
The two-argument form
import io
f = io.StringIO("abcdef")
for chunk in iter(lambda: f.read(2), ""):
print(chunk) # ab, then cd, then efiter(callable, sentinel) returns an iterator with these rules:
- Each
next()call invokescallable()with no arguments. - If the result equals
sentinel, the iterator raisesStopIteration. The sentinel value is not produced. - Otherwise the result is the next item.
The for loop never sees the sentinel. It receives "ab", "cd" and "ef", and the loop ends when f.read(2) returns "".
An equivalent generator
The behaviour is easy to state as a generator. This is a model of the semantics, not the real implementation:
def call_until(func, sentinel):
while True:
value = func()
if value == sentinel:
return
yield value
import io
f = io.StringIO("abcdef")
print(list(call_until(lambda: f.read(2), ""))) # ['ab', 'cd', 'ef']Thinking in these terms explains most of the behaviour below. The comparison uses ==, the callable takes no arguments, and the sentinel is discarded.
Why the callable takes no arguments
iter() calls callable() bare. To pass arguments, wrap the call in a lambda, or bind them with functools.partial:
import hashlib
import io
from functools import partial
def sha256_of(stream, chunk_size=8192):
digest = hashlib.sha256()
for chunk in iter(partial(stream.read, chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
data = b"hello world" * 1000
print(sha256_of(io.BytesIO(data)) == hashlib.sha256(data).hexdigest()) # Truepartial(stream.read, chunk_size) creates a new callable with the argument already filled in. It does the same job as lambda: stream.read(chunk_size). Both are fine. partial is slightly shorter and avoids a late-binding surprise: a lambda looks up stream and chunk_size when it is called, not when it is created. That matters if the lambda is built inside a loop and those names change.
The memory behaviour is the point of this idiom. At any moment only one chunk is in memory, so the same function hashes a 10 KB file or a 50 GB one.
Where this idiom fits
Use it when the source is "a function you call repeatedly" and the end is signalled by a value:
- Binary file or socket reads:
iter(partial(sock.recv, 4096), b""). - Line reads with an explicit end marker:
iter(f.readline, ""). Blank lines come back as"\n", so only end of file returns"". For plain text files you don't need this, becausefor line in falready does the same thing. - Interactive input:
iter(input, "quit")yields lines until the user typesquit. - Any stateful callable, such as a work queue:
from collections import deque
tasks = deque(["parse", "validate", "save"])
for task in iter(lambda: tasks.popleft() if tasks else None, None):
print("running", task)Here None is the sentinel. It is safe because no real task is None. If None could be a valid item, choose a unique sentinel, such as object(), that your callable returns when it is empty.
Don't use it when the object is already iterable. for line in f is clearer than iter(f.readline, "").
Properties of the returned iterator
The result is a callable_iterator. It is a normal iterator, so it can be passed to list(), sum(), zip(), itertools.islice() and so on. It is also single-use. Once it hits the sentinel, it stays finished, even if the callable would later return real values:
values = iter([1, 2, 0, 3])
it = iter(lambda: next(values), 0)
print(list(it)) # [1, 2]
print(list(it)) # []
print(next(values)) # 3The source still holds 3, but it is closed for good. To read more, create a new two-argument iterator.
If the callable itself raises StopIteration, iteration also ends. In the example above, an empty values would stop it without a sentinel ever being returned. Other exceptions propagate to your loop as usual.
The sentinel check also costs nothing extra for laziness: the callable runs only when next() is called, so nothing is read ahead.
Common errors
Passing the result instead of the callable
import io
f = io.StringIO("abcdef")
try:
iter(f.read(2), "") # wrong: calls read now and passes "ab"
except TypeError as e:
print(e)This raises TypeError with a message like iter(v, w): v must be callable, because "ab" is a string, not a function. The fix is to pass a callable that does the call later: lambda: f.read(2) or partial(f.read, 2).
A related slip is writing iter(f.read, "") with no size. That is legal, but read() returns the whole file in one call, then "" on the next call. You get one giant chunk, which defeats the purpose.
A sentinel of the wrong type
The comparison is result == sentinel. If the types never compare equal, the sentinel never matches and the loop doesn't end:
import io
from itertools import islice
f = io.StringIO("abcdef")
it = iter(lambda: f.read(2), b"") # bytes sentinel on a text stream
print(list(islice(it, 5))) # ['ab', 'cd', 'ef', '', '']A text stream returns "" at end of file, and "" == b"" is False, so this iterator is infinite. The islice call is the only reason the example stops. The rule is: text streams use "", binary streams use b"".
Sentinels that never compare equal
Some values are never equal to themselves under ==, such as float("nan"). Using one as a sentinel never matches. Compare with a value that supports normal equality, or write an explicit while loop with an is test.
Valid data that equals the sentinel
Because the sentinel is dropped, any real item equal to it ends the loop early. For iter(input, ""), the first empty line ends the loop, which may not be what you want. If an empty line is valid input, choose another sentinel such as "quit".
Expecting to reuse or restart
Wrapping the same callable in two separate iter(...) calls gives two independent iterators, but they share the underlying source. A second iterator on a partly read file starts where the first stopped, not at the beginning.
Choosing between the alternatives
| Situation | Better choice |
|---|---|
| Source is a file opened for text lines | `for line in f` |
| Source is a binary stream read in chunks | `iter(partial(f.read, n), b"")` |
| The stop test is more complex than `==` | A generator function with an explicit `if` and `return` |
| The end is signalled by an exception, not a value | A generator with `try`/`except`, or a `while` loop |
| The stop value could also be real data | A unique sentinel such as `object()`, or an explicit loop |
The two-argument iter() is a small tool. It handles one pattern, "call until a value appears", and handles it in one line. When the logic needs anything more, switch to a generator function.
Exercise
A text file is opened with open("log.txt", "rb"). Write a for loop header that reads it in 1024-byte chunks until end of file, and explain why the sentinel is b"" rather than "".
Show answer
for chunk in iter(lambda: f.read(1024), b""): (or iter(partial(f.read, 1024), b"")). Mode "rb" opens the file in binary mode, so read() returns bytes and returns b"" at end of file. Since "" == b"" is False, a "" sentinel would never match and the loop would never end.
Exercise
What does this print, and why does the last line not print 4? values = iter([5, 6, 0, 4]) it = iter(lambda: next(values), 0) print(list(it)) print(list(it)) print(next(values))
Show answer
It prints [5, 6], then [], then 4. The first list(it) stops when the callable returns 0, the sentinel, which is discarded. The iterator is then finished, so the second list(it) is empty and calls nothing. The 0 was consumed from values, so the next item left in values is 4, and next(values) prints 4.
Exercise
Rewrite the loop iter(lambda: tasks.popleft() if tasks else None, None) as a generator function, and say when you would prefer the generator.
Show answer
def drain(tasks): followed by while tasks: and yield tasks.popleft(). The generator needs no sentinel, so it works even when None is a valid task. Prefer it when the stop condition is not a simple equality test on one returned value, or when a valid item could equal the sentinel.