What is the difference between raise StopIteration and a return statement in generators?

There’s no need to explicitly raise StopIteration as that’s what a bare return statement does for a generator function – so yes they’re the same. But no, just using return is more Pythonic. From: http://docs.python.org/2/reference/simple_stmts.html#the-return-statement (valid to Python 3.2) In a generator function, the return statement is not allowed to include an expression_list. In that … Read more

“RuntimeError: generator raised StopIteration” every time I try to run app

To judge from the file paths, it looks like you’re running Python 3.7. If so, you’re getting caught by new-in-3.7 behavior: PEP 479 is enabled for all code in Python 3.7, meaning that StopIteration exceptions raised directly or indirectly in coroutines and generators are transformed into RuntimeError exceptions. (Contributed by Yury Selivanov in bpo-32670.) Before … Read more

Why does next raise a ‘StopIteration’, but ‘for’ do a normal return?

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 … Read more