Home >Backend Development >Python Tutorial >Can Returning Inside Generators in Python 3.3 Substitute Raise StopIteration Exceptions?
Returning inside a Generator: A Python 3.3 Innovation
In previous Python versions, using both return and yield within the same function definition would result in an error. However, Python 3.3 introduced a significant change.
Consider the following code:
<code class="python">def f(): return 3 yield 2</code>
In this code, the return statement appears before the yield statement. According to the new behavior, "return
When the function next is called on the generator object, it throws a StopIteration exception with the value 3, which is equivalent to returning 3. However, this value cannot be directly retrieved because the generator has terminated. Instead, the value can be accessed as the value attribute of the exception object.
<code class="python">x = f() try: x.__next__() except StopIteration as e: print(e.value) # Outputs 3</code>
Moreover, if the generator is used with the yield from syntax, it acts as the return value.
<code class="python">def g(): x = yield from f() print(x) for _ in g(): pass</code>
In this case, the output is 1 (the return value of f), but 2 is not printed since the generator has terminated.
The above is the detailed content of Can Returning Inside Generators in Python 3.3 Substitute Raise StopIteration Exceptions?. For more information, please follow other related articles on the PHP Chinese website!