liveBook · Manning

Yield

As explained in Python Workout, Second Edition

yield is a Python statement or expression that produces a value from a generator function while suspending its execution for later resumption.

Use yield when a function should produce values one at a time instead of computing every result immediately. Calling such a generator function returns a generator object; execution begins when iteration requests a value. section 11.4

Each yield returns its value to the caller and suspends the function at that point. A later next call resumes execution after the yield, preserving local variables and parameters in the generator’s single stack frame. section 11.15 section 11.19

Keep these generator behaviors in mind:

  • A for loop repeatedly requests values until the generator reaches the end of its function, when StopIteration occurs automatically. section 11.4
  • Use yield to continue producing values; use return to exit the generator completely. Do not explicitly raise StopIteration inside a generator. section 11.17
  • Use retained state for incremental calculations, such as measuring the time since the previous iteration. section 11.19
  • Prefer a generator function when it expresses iteration more simply than a class implementing the iterator protocol. section 11.23
def foo():
    yield 1
    yield 2
    yield 3

This minimal generator yields three values in sequence, pausing after each one. section 11.4

g = foo()
for one_item in g:
    print(one_item)

Iteration drives the generator: each loop pass requests the next value and prints it. section 11.4

How Python Workout, Second Edition covers it

How deep it goes
Explains suspension, resumption, automatic termination, and retained local state across iterations.
Examples
Uses a three-value foo generator, for-loop consumption, iterable chaining, and elapsed-time reporting.
What it assumes
Assumes familiarity with functions, for loops, next, and the iterator protocol while practicing generator construction.
What you can do after
Build it from scratch using generator functions that yield sequences while preserving state between requests.
How it connects
Connects yield to generator functions, iterators, the iterator protocol, generator expressions, and StopIteration.

Also explained in

Compare how 10 books explain yield →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.