liveBook · Manning

Generator

As explained in Python Concurrency with asyncio

A generator is a Python iterator object that produces values lazily by suspending and resuming execution around yield points.

A generator is a Python iterator that produces a sequence lazily. A function containing yield pauses at each yielded value and resumes when iteration advances, avoiding storage of the entire sequence in memory. section 5.7.1

Generators support several closely related iteration patterns:

  • Calling a generator function creates a generator object without immediately running its loop. section 5.7.1
  • Calling next advances execution to the next yield; a for loop can advance through all yielded values. section 5.7.1
  • Asynchronous generators combine yield with await and are consumed using async for, making delayed values available incrementally. section 5.7.1
  • Older asyncio code used generator-based coroutines with yield from before async and await syntax. section 14.5.1

Lazy integer production

Define positive_integers(until) with a loop that yields each integer. Calling positive_integers(2) creates a generator; successive next calls produce 0 and 1 without first building a list. section 5.7.1

Listing 5.13 A synchronous generator
def positive_integers(until: int):
    for integer in range(until):
        yield integer
 
 
positive_iterator = positive_integers(2)
 
print(next(positive_iterator))
print(next(positive_iterator))

Inspect the synchronous generator listing showing yield, generator creation, and explicit next calls. section 5.7.1

How Python Concurrency with asyncio covers it

How deep it goes
Explains creation, suspension, resumption, next, for, async for, and generator-based coroutines through runnable examples.
Examples
Demonstrates integer generators, delayed asynchronous integers, generator-based coroutines, and a custom future advanced by iteration.
What it assumes
Builds from normal Python functions and synchronous iteration before extending the model to asynchronous generators and coroutines.
What you can do after
Apply it via Python's next, for, async for, yield, and yield from constructs to produce values incrementally.
How it connects
Connects generators with iterators, asynchronous generators, coroutines, awaitables, futures, and event loops.

Also explained in

Compare how 12 books explain generator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.