Should a Python generator raise an exception when there are no more elements to yield?

The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for you.


It doesn't have to, but it can raise a StopIteration.

The more normal way to end the iteration is to let the function end and return naturally, or to use a return statement. This will cause a StopIteration to be raised on your behalf.

Tags:

Python