Your own iterator: __iter__ and __next__
🌍 In real life. At a bank, a ticket machine hands out queue numbers. Each press gives the next number; the machine remembers where it is up to; when the roll runs out, it says so. Nobody needs every number printed in advance.
A for loop talks to whatever it loops over in exactly that way. The idea in one sentence: for x in obj first calls iter(obj), which runs obj.__iter__() to get an iterator, then calls next() on it, which runs __next__(), again and again until __next__ raises StopIteration. Write those two methods, and your own class works in a for loop.
Its words:
- iterable: something you can loop over; it has
__iter__, which hands back an iterator - iterator: the thing that hands out items one at a time; it has
__next__(and an__iter__that returns itself) - StopIteration: the error
__next__raises to say "no more"; a for loop catches it and ends quietly - iterator protocol: these two methods together
What for n in Countdown(3) really does, step by step:
it = iter(cd)callscd.__iter__(), which returnscditselfnext(it)calls__next__():ngoes from 3 to 2, and 3 comes back- again: 2, then 1
- the fourth call finds
nis 0 and raises StopIteration, so the loop ends
A generator (Lesson 26.2) does all of this for you. Watch next() pull values from the generator version of a countdown; your class must do each of these steps by hand: remember where it is, give back the next value, and raise StopIteration at the end.
class Countdown:
def __init__(self, start):
self.n = start # where it is up to
def __iter__(self):
return self # it is its own iterator
def __next__(self):
if self.n == 0:
raise StopIteration # nothing left: the for loop stops
self.n -= 1
return self.n + 1
for n in Countdown(3):
print(n)
it = iter(Countdown(2)) # what the for loop does by hand
print(next(it), next(it))
try:
next(it)
except StopIteration:
print("StopIteration: nothing left")Why one object can be looped only once. Countdown's __iter__ returns the object itself, so the object is its own iterator, and its n only goes down. After one full loop, n is 0 and a second loop gets nothing. A list behaves differently: it is an iterable but not an iterator, so each iter(my_list) makes a fresh iterator that starts from the beginning.
To make your class loopable again and again, give it an __iter__ that makes a new iterator each time. The shortest way is to write __iter__ as a generator, with yield: every call starts a new one.
class Countdown:
def __init__(self, start):
self.n = start # where it is up to
def __iter__(self):
return self # it is its own iterator
def __next__(self):
if self.n == 0:
raise StopIteration # nothing left: the for loop stops
self.n -= 1
return self.n + 1
c = Countdown(2)
print(list(c), list(c)) # the second loop finds nothing left
class Playlist:
def __init__(self, songs):
self.songs = songs
def __iter__(self): # a generator: a fresh iterator every time
for song in self.songs:
yield song.title()
p = Playlist(["dhaka", "rain"])
print(list(p), list(p))Mistakes and edge cases.
- forgetting StopIteration: a
__next__that just returns None at the end makes the for loop run forever, printing None - returning instead of raising:
return StopIterationhands back the error as a value; it must beraise StopIteration __iter__that doesn't return an iterator: withoutreturn selfit returns None, anditer()stops with a TypeError- looping the same iterator twice: the second loop is empty, as above; make a new one, or use a generator
__iter__ - a for loop hides StopIteration,
next()doesn't: callingnext()past the end raises it, so catch it or pass a default:next(it, None)
Quiz
What does this print?
class Countdown: def __init__(self, start): self.n = start # where it is up to def __iter__(self): return self # it is its own iterator def __next__(self): if self.n == 0: raise StopIteration # nothing left: the for loop stops self.n -= 1 return self.n + 1 print(list(Countdown(3)))What does this print?
class Countdown: def __init__(self, start): self.n = start # where it is up to def __iter__(self): return self # it is its own iterator def __next__(self): if self.n == 0: raise StopIteration # nothing left: the for loop stops self.n -= 1 return self.n + 1 c = Countdown(2) for n in c: print(n) for n in c: print("again", n)What does a for loop call first on the thing it loops over?
- __iter__ (through iter()), to get an iterator
- __next__, straight away
- __len__, to know how many items there are
What does this print?
class Countdown: def __init__(self, start): self.n = start # where it is up to def __iter__(self): return self # it is its own iterator def __next__(self): if self.n == 0: raise StopIteration # nothing left: the for loop stops self.n -= 1 return self.n + 1 it = iter(Countdown(1)) print(next(it), next(it, "done"))A for loop over Upto(2) never ends. Which line is wrong?
class Upto: def __init__(self, n): self.i, self.n = 0, n def __iter__(self): return self def __next__(self): if self.i == self.n: return None self.i += 1 return self.i
Coding tasks
Finish
Countdown(start)so that looping over it givesstart,start - 1, … down to 1. It is its own iterator, so one object can be looped once.Evens(limit)should give the even numbers from 0 up to (not including)limit, and work in any number of loops. Rewrite its__iter__as a generator (withyield) so each loop starts fresh.