Iterators
In typical design pattern parlance, an iterator is an object with a next()
method and a done()
method; the latter returns True
if there are no items left in the sequence. In a programming language without built-in support for iterators, the iterator would be looped over like this:
while not iterator.done(): item = iterator.next() # do something with the item
In Python, iteration is a special feature, so the method gets a special name, __next__
. This method can be accessed using the next(iterator)
built-in. Rather than a done
method, the iterator protocol raises StopIteration
to notify the loop that it has completed. Finally, we have the much more readable for item in iterator
syntax to actually access items in an iterator instead of messing around with a while
loop. Let's look at these in more detail.
The iterator protocol
The abstract base class Iterator
, in the collections.abc
module, defines the iterator protocol in Python. As mentioned, it must have a __next__
method that...