Creating custom iterators
The Pythonic secret that enables comprehensions to find all of the entries in a list, range, or other collection is an iterator. Supporting iterators in your classes opens them up for use in comprehensions, for…in
loops, and anywhere that Python works with collections. Your collection must implement a method called __iter__()
, which returns the iterator.
The iterator itself is also a Python object with a simple contract. It must provide a single method, __next__()
. Each time __next__()
is called, the iterator returns the next value in the collection. When the iterator reaches the end of the collection, __next__()
raises StopIteration
to signal that the iteration should terminate.
If you’ve used exceptions in other programming languages, you may be surprised by this use of an exception to signal a fairly commonplace situation. After all, plenty of loops reach an end, so it’s not exactly an exceptional circumstance. Python is not so...