tags:

views:

71

answers:

2

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

Which one?

+7  A: 

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.

Mark Byers
This answers my vague question, but I was wondering to know if in my code I should manually raise it.
Juanjo Conti
+3  A: 

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.

Shane Holloway
This is what I was looking for!
Juanjo Conti
Reference: http://www.python.org/dev/peps/pep-0255/
S.Lott