In Python, StopIteration is an exception which occurred by built-in next() and __next__() method in iterator to signal that iteration is done for all items and no more to left to iterate.
Iterator in Python uses the two methods, i.e. iter() and next(). The next() method raises an StopIteration exception when the next() method is called manually. The best way to avoid this exception in Python is to use normal looping or use it as a normal iterator instead of writing the next() method again and again.
The for
loop listens for StopIteration
explicitly.
The purpose of the for
statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done; for
doesn't catch other exceptions raised by the object being iterated over, just that one.
That's because StopIteration
is the normal, expected signal to tell whomever is iterating that there is nothing more to be produced.
A generator function is a special kind of iterator; it indeed raises StopIteration
when the function is done (i.e. when it returns, so yes, return None
raises StopIteration
). It is a requirement of iterators; they must raise StopIteration
when they are done; in fact, once a StopIteration
has been raised, attempting to get another element from them (through next()
, or calling the .next()
(py 2) or .__next__()
(py 3) method on the iterator) must always raise StopIteration
again.
GeneratorExit
is an exception to communicate in the other direction. You are explicitly closing a generator with a yield
expression, and the way Python communicates that closure to the generator is by raising GeneratorExit
inside of that function. You explicitly catch that exception inside of countdown
, its purpose is to let a generator clean up resources as needed when closing.
A GeneratorExit
is not propagated to the caller; see the generator.close()
documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With