HOME | DD

default-cube — Van Rossum's Triangle

#coroutine #eventloop #python_language #generator_function
Published: 2017-05-10 08:16:07 +0000 UTC; Views: 1411; Favourites: 1; Downloads: 0
Redirect to original
Description This is a diagram I threw together to try to make sense of the intricate web of interrelationships between generators , coroutines and mainline code in Python 3.5 and later.

Basically, both generators and coroutines have “send()” methods that can be used to start them running from the mainline (a “mainline” being whatever code starts executing to begin with in a Python program, plus whatever functions/methods it calls etc). A coroutine can use the “await”-construct on any “awaitable” object (one that has an “__await__()” method) to transfer control to it. Generators are awaitable. A generator can execute a “yield”-construct to transfer control back to the mainline. The mainline can then use a “send()” method call to resume execution; if the generator then does a “return” (or, equivalently, its execution falls off the end of the function), this returns control to the “await”ing coroutine.

Coroutines can also use “await” to transfer control between each other.

And, just for added fun, generators and coroutines can also invoke “send()” methods on other generators and coroutines, thereby becoming mainlines within mainlines.

This web of language mechanisms is the basis on which the entire asyncio event-loop architecture is built.
Related content
Comments: 0