Home > Backend Development > Python Tutorial > How Do Return and Yield Work in Python Generators?

How Do Return and Yield Work in Python Generators?

Mary-Kate Olsen
Release: 2024-10-25 03:16:02
Original
519 people have browsed it

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>
Copy after login

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 within a generator is now equivalent to raise StopIteration(). Consequently, the StopIteration exception contains the value 3 in the code snippet above. Accessing the value attribute of the exception will retrieve this value.

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template