Home >Backend Development >Python Tutorial >How Do Generator Yield and Return Interact in Python?

How Do Generator Yield and Return Interact in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 06:05:291000browse

How Do Generator Yield and Return Interact in Python?

Generator Yield and Return Interplay in Python

Prior to Python 3.3, combining return and yield within a function definition would result in an error. However, in Python 3.3 and later, this behavior has been updated.

Python 3.3 Behavior

In Python 3.3, the return statement within a generator function is now treated similarly to a raise StopIteration() statement. As a result, using both return and yield in a generator is now equivalent to raising a StopIteration exception with the specified value.

Example:

Consider the following code:

<code class="python">def f():
    return 3
    yield 2</code>

When the f() function is called, it will no longer raise a runtime error. Instead, the __next__() function of the generator object (x) will raise a StopIteration exception with the value 3:

<code class="python">x = f()
try:
    print(x.__next__())
except StopIteration as e:
    print(e.value)  # Prints "3"</code>

Yielding the Returned Value

If a generator function is delegated using the yield from syntax, the returned value of the return statement will be the result of the delegated generator.

Example:

<code class="python">def f():
    return 1
    yield 2

def g():
    x = yield from f()
    print(x)

# Iterate through the generator:
for _ in g():
    pass  # Prints "1"</code>

In this example, the f() generator is delegated to the g() generator using yield from. As a result, the value returned by return 1 in the f() generator becomes the result of the g() generator.

The above is the detailed content of How Do Generator Yield and Return Interact in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn