Home >Backend Development >Python Tutorial >How Do Return and Yield Work in Python Generators?
Return and Yield in Python Generators
In Python prior to version 3.3, using both return and yield statements simultaneously within a generator function definition would result in an error. However, this behavior has changed in Python 3.3.
Consider the following code:
<code class="python">def f(): return 3 yield 2</code>
Calling x = f() will create a generator, and x.__next__() will raise a StopIteration exception. This behavior differs from simply return 3, which would have returned the value 3.
This is because in Python 3.3, return
Additionally, yield from allows делегировать generators to other generators. Consider the following example:
<code class="python">def f(): return 1 yield 2 def g(): x = yield from f() print(x) for _ in g(): pass</code>
This code prints 1. g delegates execution to f, and the value returned by f (i.e., 1) is assigned to x. However, the yield 2 statement in f is not executed since the execution has been delegated to g.
The above is the detailed content of How Do Return and Yield Work in Python Generators?. For more information, please follow other related articles on the PHP Chinese website!