In this code I have class name Iter that contains Two dunder methods __iter__ and __next__. In __iter__method I set self.current equal to zero and return self. In next method I increase
self.current += 1. When it reaches 10 I want it to raise a StopIteration exception.
class Iter:
def __iter__(self):
self.current = 0
return self
def __next__(self):
self.current += 1
if self.current == 10:
raise StopIteration
return self.current
it = Iter()
for i in it:
print(i)
Your iterator already raises
StopIteration, which is caught by theforloop in order to stop the iteration. This is just howforloops work normally.You can see this easily in your iterator if you add a
print:If you want to re-raise
StopIterationafter your iterator is exhausted, one option is just to raise one manually after theforloop:Another is to change the way you do the iteration so that the
StopIterationisn't caught: