Sub topic 10
Pitfalls: exhausted iterators and re-iteration
This chapter assumes you know the iterator protocol (__iter__, __next__, StopIteration) and can write generator functions and generator expressions. It covers the bugs that come from one fact: an iterator is a one-way, single-use object.
Why iterators run out
An iterator keeps its position internally. Each next() moves that position forward, and nothing moves it back. When the underlying data runs out, the iterator raises StopIteration. By convention it keeps raising it on every later call.
A generator has the same life cycle. Once its body finishes, it cannot restart.
The failure is usually silent. Looping over an exhausted iterator is legal: the loop body runs zero times, and no error is raised.
nums = iter([1, 2, 3])
print(sum(nums)) # 6
print(sum(nums)) # 0, nothing is left, and no error is raisedIterable or iterator?
A reusable object is an iterable that produces a fresh iterator each time you call iter() on it. Lists, tuples, strings, dicts, sets and range all work this way. A one-shot object is an iterator whose __iter__ returns itself.
| Reusable (new iterator per loop) | One-shot (iterator) |
|---|---|
| `list`, `tuple`, `str`, `set` | generator functions and expressions |
| `dict` and its `.keys()`, `.values()`, `.items()` views | `map`, `filter`, `zip`, `enumerate` |
| `range` | file objects |
| Your own class with a generator `__iter__` | `reversed(...)` and `iter(...)` results |
You can test any object directly. An iterator returns itself from iter().
from collections.abc import Iterator
def is_one_shot(obj):
return iter(obj) is obj
print(is_one_shot([1, 2])) # False
print(is_one_shot(x for x in [1, 2])) # True
print(isinstance(map(str, [1]), Iterator)) # TruePitfall 1: consuming twice
Any function that loops over its argument consumes it if the argument is an iterator. Two passes over the same iterator are a common source of bugs.
def average(values):
total = sum(values)
count = sum(1 for _ in values)
return total / count
print(average([2, 4, 6])) # 4.0
print(average(x for x in [2, 4, 6])) # ZeroDivisionErrorThe list works because each sum call starts a new iteration. The generator is empty after the first sum, so count is 0.
Files behave the same way. The second loop below prints nothing.
import io
f = io.StringIO("one\ntwo\n")
print([line.strip() for line in f]) # ['one', 'two']
print([line.strip() for line in f]) # []Pitfall 2: partial consumption
Anything that pulls values from an iterator advances it for everyone else. This includes next(), for, list(), in, sum(), min() and max().
it = iter("abcde")
first = next(it)
rest = list(it)
print(first, rest) # a ['b', 'c', 'd', 'e']
print(list(it)) # []The in operator is an easy one to miss. On an iterator it scans forward until it finds a match, and the matched item and everything before it are gone.
it = iter(range(10))
print(3 in it) # True
print(next(it)) # 4Leaving a loop with break does not close or reset the iterator. You can resume where you stopped, but the item that triggered the break is already consumed.
it = iter([1, 2, 3, 4, 5])
for n in it:
if n == 2:
break
print(list(it)) # [3, 4, 5] (2 is gone)Resuming this way is a legitimate technique, for example to read a header and then the body from the same file. It is a bug only when you did not intend it.
Pitfall 3: `zip` can drop an item
zip stops when its shortest input ends. It asks its inputs for values in order. If an earlier input yields a value and a later one is empty, the earlier value is lost.
a = iter([1, 2, 3])
b = iter([10, 20])
print(list(zip(a, b))) # [(1, 10), (2, 20)]
print(list(a)) # [] because 3 was taken from a and discarded
a = iter([1, 2, 3])
b = iter([10, 20])
print(list(zip(b, a))) # [(10, 1), (20, 2)]
print(list(a)) # [3] because b ended first, so a was not askedIf you keep using an iterator after passing it to zip, the order of the arguments matters. Put the iterator you plan to keep using last.
Pitfall 4: testing a generator for emptiness
Generators have no length, and every generator object is truthy, even one that will yield nothing.
gen = (x for x in [])
print(bool(gen)) # True
try:
len(gen)
except TypeError as exc:
print(exc) # object of type 'generator' has no len()An if gen: check therefore never detects an empty generator. To test for emptiness you must try to take a value, and that value is consumed. The two-argument form of next() returns a default instead of raising.
from itertools import chain
gen = (x for x in [5, 6])
sentinel = object()
first = next(gen, sentinel)
if first is sentinel:
print("empty")
else:
gen = chain([first], gen) # put the value back
print(list(gen)) # [5, 6]The chain call puts the peeked value back in front of the rest.
Fixes
You have four ways to deal with an iterator that must be read more than once. They differ in memory use and in who owns the decision.
Create a new iterator
If you can build the iterator again cheaply, do that. Call the generator function again, or reopen the file.
def squares(n):
for i in range(n):
yield i * i
print(sum(squares(4))) # 14
print(max(squares(4))) # 9Materialize it
list(it) stores every item once and allows any number of passes. Do this at a boundary, for example at the top of a function that needs two passes.
def average(values):
values = list(values) # safe for lists and for iterators
return sum(values) / len(values)
print(average(x for x in [2, 4, 6])) # 4.0The cost is memory proportional to the data. This defeats the purpose of laziness for large or infinite streams, so use it only when the data fits in memory.
Make the source re-iterable
Wrap the recipe for the stream, not the stream itself. The class below calls a factory function each time a loop starts, so every loop gets a fresh iterator.
class Reiterable:
def __init__(self, factory):
self.factory = factory
def __iter__(self):
return self.factory()
squares = Reiterable(lambda: (x * x for x in range(3)))
print(list(squares)) # [0, 1, 4]
print(list(squares)) # [0, 1, 4]
print(sum(squares)) # 5A function that loops over its argument twice now works with this object. It is lazy, but the work is repeated on each pass.
Split with `tee`
itertools.tee makes independent iterators from one source.
from itertools import tee
a, b = tee(x * x for x in range(4))
print(sum(a)) # 14
print(max(b)) # 9Two rules apply. First, stop using the original iterator after calling tee, because it shares state with the copies. Second, tee buffers every item that one copy has read and another has not. If you drain a completely before touching b, the whole stream sits in memory. In that case list() is simpler and does the same job. tee suits copies that advance roughly in step.
A related trap: `StopIteration` inside a generator
If a StopIteration escapes from the body of a generator, Python converts it to a RuntimeError. This most often happens when you call next() on another iterator inside a generator without a default.
def pairs(items):
it = iter(items)
while True:
yield next(it), next(it) # RuntimeError when it runs out
def pairs_fixed(items):
it = iter(items)
for first in it:
second = next(it, None)
yield first, second
print(list(pairs_fixed([1, 2, 3]))) # [(1, 2), (3, None)]Prefer a for loop or the default argument to next(). Both handle the end of the data without letting a stray StopIteration escape.
Checklist
- Before passing an iterator to a function, check whether the function loops more than once.
- When you write such a function, either call
list()on the argument or document that you need a re-iterable. - Do not test generators with
if gen:orlen(gen). - Remember that
in,min,max,sum,listandsortedall consume an iterator. - Order
ziparguments so the iterator you keep using comes last. - Choose among re-creating,
list(), a factory-based class, andtee, according to memory and cost of repeating the work.
Exercise
What do gen = (n for n in range(4)), print(2 in gen) and print(list(gen)) print, and why?
Show answer
They print True and then [3]. The in operator advances the generator through 0, 1 and 2 until it finds 2, so those values are consumed. Only 3 remains for list(gen).
Exercise
A function report(rows) loops over rows once to compute a total and again to print each row. It works with a list but prints nothing in its second loop when given a generator. Give two ways to fix it without changing the callers, and name one cost of each.
Show answer
Fix 1: put rows = list(rows) at the top of the function. The cost is that all rows are held in memory at once. Fix 2: loop only once, collecting the rows you need to print while computing the total. This also keeps all printed rows in memory, though you can avoid that if you can print and add to the total in the same pass. A tee call inside the function is a third option, but it buffers the rows if one copy is read fully before the other.