I’m curious about the difference between using raise StopIteration and a return statement in generators.
For example, is there any difference between these two functions?
def my_generator0(n):
for i in range(n):
yield i
if i >= 5:
return
def my_generator1(n):
for i in range(n):
yield i
if i >= 5:
raise StopIteration
I’m guessing the more “pythonic” way to do it is the second way (please correct me if I’m wrong), but as far as I can see both ways raise a StopIteration exception.
There’s no need to explicitly raise
StopIterationas that’s what a barereturnstatement does for a generator function – so yes they’re the same. But no, just usingreturnis more Pythonic.From: http://docs.python.org/2/reference/simple_stmts.html#the-return-statement (valid to Python 3.2)
Or as @Bakuriu points out – the semantics of generators have changed slightly for Python 3.3, so the following is more appropriate: