Sub topic 2
The iterator protocol: __iter__, __next__ and StopIteration
This chapter assumes you can write Python functions, classes and loops, and that you know what a special (dunder) method is. It also assumes you know how try/except works. Everything Python does when it loops over data rests on a small contract called the iterator protocol. This chapter covers that contract and the errors people hit when they get it wrong. Later chapters build iterator classes and generators on top of it.
Two methods, two roles
The protocol has two special methods. Each has a different job.
| Method | Called by | What it must do |
|---|---|---|
| `__iter__(self)` | `iter(obj)` | Return an iterator |
| `__next__(self)` | `next(obj)` | Return the next value, or raise `StopIteration` when there are none left |
Two terms follow from this:
- An iterable is any object whose
__iter__returns an iterator. Lists, tuples, strings, dicts, sets and files are iterables. - An iterator is any object that implements
__next__, and also__iter__returning itself. It remembers where it is in the sequence.
Every iterator is also an iterable. The reverse is not true. A list is iterable, but it is not an iterator, because it has no __next__.
The built-ins iter() and next()
You almost never call __iter__ and __next__ directly. You call the built-in functions that wrap them.
numbers = [10, 20]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("exhausted")iter(numbers) calls numbers.__iter__(), which returns a new list iterator. Each next(it) calls it.__next__(). When the list has no more items, __next__ raises StopIteration.
next() accepts an optional second argument. If you pass it, Python returns that value instead of raising when the iterator is exhausted.
it = iter([1])
print(next(it, "empty")) # 1
print(next(it, "empty")) # emptyStopIteration is a signal, not a failure
StopIteration is an exception, but it is used for flow control. It means "there is nothing more to give you." The consumer, such as a for loop, list() or sum(), catches it and finishes normally. You see it as an error only when you call next() yourself and forget to handle it.
The protocol is designed this way so iterators can return any value, including None, 0 or an empty string. Returning a special "end" value would make that value impossible to use as data. An exception cannot be confused with data.
Containers hand out fresh iterators
A list does not keep a position. The iterator does. This is why each call to iter() on a list gives you an independent cursor.
data = ["a", "b", "c"]
first = iter(data)
second = iter(data)
print(next(first), next(first), next(second)) # a b aThe two iterators move separately over the same list. Two nested loops over the same list rely on this.
An iterator behaves differently. Calling iter() on an iterator returns the same object.
nums = [1, 2, 3]
it = iter(nums)
print(iter(nums) is nums) # False: a new iterator each time
print(iter(it) is it) # True: an iterator returns itselfThis is why every iterator must define __iter__ that returns self. It lets an iterator be used anywhere an iterable is expected, such as in a for statement.
Watching the protocol happen
The class below does nothing except print when Python calls its methods. It is a minimal full implementation of the protocol.
class Trace:
def __init__(self, items):
self.items = items
self.pos = 0
def __iter__(self):
print("__iter__ called")
return self
def __next__(self):
print("__next__ called")
if self.pos >= len(self.items):
raise StopIteration
value = self.items[self.pos]
self.pos += 1
return value
for x in Trace(["a"]):
print("got", x)The output is:
__iter__ called
__next__ called
got a
__next__ called__iter__ runs once, at the start of the loop. __next__ runs before every pass, including one extra call at the end. That last call raises StopIteration and ends the loop. The next chapter covers the for loop in detail.
The sequence of calls looks like this:
The contract an iterator must keep
The protocol has rules beyond the method names.
__iter__on an iterator returnsself.__next__returns one value per call, in order.- After
__next__raisesStopIteration, every later call must also raise it. An exhausted iterator stays exhausted.
Built-in iterators follow rule 3.
it = iter([1])
print(list(it)) # [1]
print(list(it)) # []The second list(it) is empty because the iterator is already at its end. It does not rewind. This is the cause of many bugs, and the pitfalls chapter returns to it. If you write your own iterator and it "wakes up" after raising StopIteration, code that checks for exhaustion twice will behave unpredictably.
Checking for the protocol
The collections.abc module defines two abstract classes that describe the protocol.
from collections.abc import Iterable, Iterator
nums = [1, 2, 3]
it = iter(nums)
print(isinstance(nums, Iterable)) # True
print(isinstance(nums, Iterator)) # False
print(isinstance(it, Iterable)) # True
print(isinstance(it, Iterator)) # TrueIterable checks for __iter__. Iterator checks for both __iter__ and __next__. These checks only look at whether the methods exist. They cannot tell whether your __next__ follows the contract.
If you subclass Iterator, you only need to write __next__. The base class supplies __iter__ returning self.
The older sequence protocol
Python has a second, older way to be iterable. If an object has no __iter__ but has __getitem__, iter() builds an iterator that calls __getitem__(0), __getitem__(1) and so on. It stops when IndexError is raised.
class Legacy:
def __getitem__(self, index):
if index >= 3:
raise IndexError
return index * index
print(list(Legacy())) # [0, 1, 4]This works, but isinstance(Legacy(), Iterable) is False because there is no __iter__. The only reliable test of whether an object is iterable is to call iter() on it and catch TypeError. For new code, define __iter__.
Common errors
Most mistakes with the protocol produce a TypeError with a clear message.
try:
next([1, 2, 3])
except TypeError as error:
print(error) # 'list' object is not an iterator
try:
iter(42)
except TypeError as error:
print(error) # 'int' object is not iterable- "is not an iterator": you called
next()on an iterable. Calliter()on it first. - "is not iterable": the object has neither
__iter__nor__getitem__. __iter__returns a non-iterator: if__iter__returns something without__next__,iter()raisesTypeError: iter() returned non-iterator.- Forgetting to advance state: if
__next__returns a value without updating its position, the loop never ends. The same value comes back forever. - Making a container single-use by accident: if a collection class defines
__iter__asreturn selfand keeps its position in itself, it can be looped over only once. A container should return a new iterator from__iter__.
Choosing what to implement
Use this guide when you design a class that should work in loops.
- If the object holds data and may be looped over many times, make it an iterable. Its
__iter__returns a new iterator on each call. - If the object represents a one-way stream, such as a file, a network feed or a counter, make it an iterator. Its
__iter__returnsself. - If you need both, keep them as two separate classes, or let
__iter__be a generator method. Later chapters show both approaches.
Exercise
A learner writes it = iter([1, 2, 3]), then for x in it: print(x), then runs the same for loop a second time. The second loop prints nothing. Which two facts about the protocol explain this?
Show answer
First, iter(it) on an iterator returns the same object, so the second loop does not get a fresh iterator. Second, the iterator was already exhausted by the first loop, and an exhausted iterator keeps raising StopIteration on every __next__ call. To loop twice, call iter() on the original list again, or loop over the list itself.
Exercise
What does this code print, and why? it = iter("ab") print(next(it, "-")) print(next(it, "-")) print(next(it, "-")) print(next(it, "-"))
Show answer
It prints a, b, -, -, each on its own line. A string is iterable, so iter("ab") returns a string iterator that yields "a" and then "b". After that the iterator raises StopIteration. Because next() was given the default "-", it returns that value instead of raising, and it keeps doing so on later calls because an exhausted iterator stays exhausted.