Python 3D Academyবাংলা

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:

  1. it = iter(cd) calls cd.__iter__(), which returns cd itself
  2. next(it) calls __next__(): n goes from 3 to 2, and 3 comes back
  3. again: 2, then 1
  4. the fourth call finds n is 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 StopIteration hands back the error as a value; it must be raise StopIteration
  • __iter__ that doesn't return an iterator: without return self it returns None, and iter() 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: calling next() past the end raises it, so catch it or pass a default: next(it, None)

Quiz

  1. 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)))
  2. 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)
  3. 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
  4. 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"))
  5. 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

  1. Finish Countdown(start) so that looping over it gives start, start - 1, … down to 1. It is its own iterator, so one object can be looped once.

  2. 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 (with yield) so each loop starts fresh.