Chapter 12. Iterators, generators and decorators
Python iterator objects required to support two methods while following the iterator protocol.
__iter__ returns the iterator object itself. This is used in
for and
in statements.
next method returns the next value from the iterator. If there is no more items to return then it should raise
StopIteration exception.
class Counter(object):
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
'Returns itself as an iterator object'
return self
def next(self):
'Returns the next value till current is lower than high'
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
Now we can use this iterator in our code.
>>> c = Counter(5,10)
>>> for i in c:
... print i,
...
5 6 7 8 9 10
Remember that an iterator object can be used only once. It means after it raises
StopIteration once, it will keep raising the same exception.
>>> c = Counter(5,6)
>>> next(c)
5
>>> next(c)
6
>>> next(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in next
StopIteration
>>> next(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in next
StopIteration
Using the iterator in for loop example we saw, the following example tries to show the code behind the scenes.
>>> iterator = iter(c)
>>> while True:
... try:
... x = iterator.next()
... print x,
... except StopIteration as e:
... break
...
5 6 7 8 9 10