What is the difference between raise StopIteration and a return statement in generators?
Solution 1:
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 context, a bare return indicates that the generator is done and will cause StopIteration to be raised.
Or as @Bakuriu points out - the semantics of generators have changed slightly for Python 3.3, so the following is more appropriate:
In a generator function, the return statement indicates that the generator is done and will cause StopIteration to be raised. The returned value (if any) is used as an argument to construct StopIteration and becomes the StopIteration.value attribute.
Solution 2:
As of late 2014 return
is correct and raise StopIteration
for ending a generator is on a depreciation schedule. See PEP 479 for full details.
Abstract
This PEP proposes a change to generators: when
StopIteration
is raised inside a generator, it is replaced withRuntimeError
. (More precisely, this happens when the exception is about to bubble out of the generator's stack frame.) Because the change is backwards incompatible, the feature is initially introduced using a__future__
statement.Acceptance
This PEP was accepted by the BDFL on November 22…
Rationale
The interaction of generators and StopIteration is currently somewhat surprising, and can conceal obscure bugs. An unexpected exception should not result in subtly altered behaviour, but should cause a noisy and easily-debugged traceback. Currently, StopIteration raised accidentally inside a generator function will be interpreted as the end of the iteration by the loop construct driving the generator.
…
Solution 3:
That's true, they are equivalent except that one is readable whereas the other is obscure. This dates back to the very first version of generators (PEP 255, under "Specification: Return"), and the subsequent enhancements of (such as coroutines) do not change this. 3.3's yield from
(PEP 380) extends that to return <expr>
as syntactic sugar for raise StopIteration(<expr>)
, but that doesn't change the meaning of return;
.