Using the return statement in generators

I'm trying to learn python by reading the Learning Python book, and stumbled upon the section on using return expressions in generators, and it's hard for me to wrap my head around it.

It says that when using the return in a generator function, it will throw a StopIteration exception that must be raised, which actually ends the iteration. If the return actually returned something to the function, it would violate the iterative protocol.

Here is a sample code

 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 someone explain this, as well as how to use it further in any other context. Give more examples if you can.

+2
source share
1 answer

return in the 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 want to put it there, it is obvious that increasing StopIteration means that the generator will stop giving items. In other words, the generator completes the execution - just like return signals the completion of the function. Similarly, everything that the generator iterates (for example, a for loop) will understand that it must stop trying to get values ​​from the generator.

The return value bit has been added to support some workflows using IIRC co-routines. This is a fairly advanced feature, but finds a lot of usefulness in various asynchronous contexts.

+3
source

Source: https://habr.com/ru/post/1275445/


All Articles