Sub topic 12
Making objects iterable
This chapter assumes you know how to write classes with instance attributes, and that you have used for loops and generators' yield at a basic level. It builds on the container chapter, where __getitem__ happened to make iteration work.
What a for loop does
A for loop calls two special methods on your behalf:
iter(obj)callsobj.__iter__(), which must return an iterator.- The loop calls
next(iterator)repeatedly. That callsiterator.__next__(), which returns the next value. When there are no more values, it raisesStopIteration, and the loop ends quietly.
An iterable is an object with __iter__. An iterator is an object with both __next__ and an __iter__ that returns itself. Lists are iterables, not iterators. Calling iter([1, 2]) gives you a separate iterator object.
Separate iterable and iterator
Keeping the two roles in different classes means every loop gets its own fresh position.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return CountdownIterator(self.start)
class CountdownIterator:
def __init__(self, current):
self.current = current
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]
c = Countdown(2)
print(list(c), list(c)) # [2, 1] [2, 1]Countdown stores only the starting value. Each call to iter(c) creates a new CountdownIterator, so c can be looped over any number of times.
The generator shortcut
Writing a second class is rarely necessary. A generator function used as __iter__ returns a new generator, which is a ready-made iterator, on every call.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
current = self.start
while current > 0:
yield current
current -= 1
c = Countdown(2)
print(list(c), list(c)) # [2, 1] [2, 1]
it = iter(c)
print(list(it), list(it)) # [2, 1] []The last line shows that an iterator is single-use. Once it is exhausted, it stays exhausted.
Common errors
- Returning
selffrom__iter__on a class that holds the position. The object becomes its own iterator, so a second loop sees nothing. Do this only when you really mean to build an iterator. - Forgetting
raise StopIteration. A__next__that never raises it loops forever. - Defining
__next__without__iter__.forcallsiter()first, so the object is rejected with aTypeError. - Relying on the
__getitem__fallback. If a class has no__iter__but has__getitem__, Python tries indexes 0, 1, 2 and so on untilIndexError. This works, as thePlaylistclass showed, but it is an older mechanism. Define__iter__when iteration matters.
Exercise
A class defines __iter__ as return self and __next__ that counts down from self.current. You run list(obj) twice on the same object. What does the second call return, and how do you fix it?
Show answer
The second call returns an empty list, because the first loop used up the single shared position. To fix it, make __iter__ return a new iterator each time, either by creating a separate iterator class or by writing __iter__ as a generator function that starts from the stored starting value.