Return Inside Generator with Yield
In Python 3.3, a significant change was introduced regarding the usage of return alongside yield within generator functions. Unlike Python 2, where such code would trigger an error, Python 3.3 allows it. However, the behavior differs from what one might expect.
Consider the following Python 3.3 code:
<code class="python">def f(): return 3 yield 2 x = f() print(x.__next__())</code>
If you run this code, you'll notice an exception being thrown: StopIteration: 3. This exception has two key aspects:
So, when a generator function contains both return and yield, it's like raising a StopIteration exception with the specified return value. This means that the generator will terminate, and the returned value will be available through the exception's value attribute.
In other words, while return in a generator function was previously an error, it now has a specific purpose: to terminate the generator and return a value through the exception handling mechanism.
This behavior has implications for generator delegation using the new yield from syntax in Python 3.3. For example:
<code class="python">def f(): return 1 yield 2 def g(): x = yield from f() print(x) # Iterate over generator to run it for _ in g(): pass</code>
In this code, the generator f returns 1 and then delegates to the generator g, which prints the returned value. However, you will only see 1 printed, indicating that the yield statement stops the delegation before the yield statement in f can produce the value 2.
The above is the detailed content of How does Return Affect Generator Behavior in Python 3.3?. For more information, please follow other related articles on the PHP Chinese website!