The interface for iteration

An iterable is an object that supports iteration, which, at a very high level, means that we can run a for .. in ... loop over it, and it will work without any issues. However, iterable does not mean the same as iterator.

Generally speaking, an iterable is just something we can iterate, and it uses an iterator to do so. This means that in the __iter__ magic method, we would like to return an iterator, namely, an object with a __next__() method implemented.

An iterator is an object that only knows how to produce a series of values, one at a time, when it's being called by the already explored built-in next() function. While the iterator is not called, it's simply frozen, sitting idly by until it's called again for the next value to produce. In this sense, generators are iterators.

Python concept Magic method Considerations
Iterable __iter__

They work with an iterator to construct the iteration logic.

These objects can be iterated in a for ... in ...: loop

Iterator __next__

Define the logic for producing values one at the time.

The StopIteration exception signals that the iteration is over.

The values can be obtained one by one via the built-in next() function.

In the following code, we will see an example of an iterator object that is not iterable—it only supports invoking its values, one at a time. Here, the name sequence refers just to a series of consecutive numbers, not to the sequence concept in Python, which will we explore later on:

class SequenceIterator:
def __init__(self, start=0, step=1):
self.current = start
self.step = step

def __next__(self):
value = self.current
self.current += self.step
return value

Notice that we can get the values of the sequence one at a time, but we can't iterate over this object (this is fortunate because it would otherwise result in an endless loop):

>>> si = SequenceIterator(1, 2)
>>> next(si)
1
>>> next(si)
3
>>> next(si)
5
>>> for _ in SequenceIterator(): pass
...
Traceback (most recent call last):
...
TypeError: 'SequenceIterator' object is not iterable

The error message is clear, as the object doesn't implement __iter__().

Just for explanatory purposes, we can separate the iteration in another object (again, it would be enough to make the object implement both __iter__ and __next__, but doing so separately will help clarify the distinctive point we're trying to make in this explanation).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.98.166