Write a custom Python class that follows the iterator protocol.
An object becomes an iterator when it provides two methods. The __iter__ method returns the iterator itself, and the __next__ method returns the next value in the sequence. When there are no values left, __next__ raises StopIteration so that Python knows the sequence has finished.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current
for value in Countdown(3):
print(value)
it = Countdown(2)
print(next(it))
print(next(it))
The for loop calls iter() on the object, which gives back the iterator, and then it calls next() again and again until StopIteration is raised. Because this class returns itself from __iter__, the object is both iterable and an iterator at the same time. That is the simplest design, and it is the design that generators themselves use.
Two details are worth explaining carefully. The StopIteration exception is not a real error. It is the signal that says the sequence is finished, and it must be raised by __next__ when there is nothing left. Raising any other exception would travel up the stack as a genuine failure. The second detail is that the state lives on the instance, so every new Countdown object keeps its own separate countdown.
There is an alternative design that splits the two roles in half. The container implements __iter__ and returns a different iterator object that implements __next__. That is what a list does, because iter() on a list gives you a list_iterator, and the list itself is not an iterator. You only need that split when one object should support several independent traversals at the same time. That is the case for containers, and it is rarely the case for your own classes.