Reputation: 23
I'm trying to learn python, reading by the book Learning Python, and came across the section of using the return
statement in generators, and I'm finding it difficult to wrap my head around it.
It says that while using the return
statement in a generator function, it will produce a StopIteration
exception to be raised, effectively ending the iteration. If a return
statement were actually to make the function return something, it would break the iteration protocol.
Here's the code sample
def geometric_progression(a, q):
k = 0
while True:
result = a * q**k
if result <= 100000:
yield result
else:
return
k += 1
for n in geometric_progression(2,5):
print(n)
Can anyone please explain it, and also how to use it further in any other context. Provide extra examples, if you may.
Upvotes: 2
Views: 2035
Reputation: 309831
return
in a generator is just syntactic sugar for raise StopIteration
. In python 3.3(?)+, you can also return a value (return value
== raise StopIteration(value)
).
As for why you'd want to put it there, obviously raising a StopIteration
means that the generator will stop yielding items. In other words, the generator is finished executing -- just like return
signals the end of a function's execution. Similarly, anything which is iterating over the generator (e.g. a for
loop) will understand that it should stop trying to get values from the generator.
The return value
bit was added to support some workflows using co-routines IIRC. It's a pretty advanced feature but finds lots of usefulness in various async contexts.
Upvotes: 4