2 ms·
> I talk about generators as if they were the coroutine system in Python, but in fact, they’re one of two: Python also has a completely different kind of thing
by mananaysiempre 3y ago
> I talk about generators as if they were the coroutine system in Python, but in fact, they’re one of two: Python also has a completely different kind of thing that it actually uses the name ‘coroutine’ for, in which function definitions start with async def and suspend with await.
The async and await system of coroutines in Python is in fact layered on top of the yield system, via an intermediate construct called yield from—which isn’t even technically required, it’s just that implementing it as a loop passing values through from and to the subcoroutine is exceptionally tedious when done carefully[1] and can’t be abstracted as a function call.
As a first approximation, await x in Python is equivalent to yield from x.__await__(). It should have been completely equivalent, arguably, but history got in the way.
David Beazley has a talk[2] where he walks you through implementing an async runtime (to put it pompously) and you can see how the whole thing hangs together. It’s really quite simple, and in my experience it’s much better than trying to wrap your head around the asyncio docs, because while the language-level foundations are extremely nice and simple, asyncio the stdlib module just kind of sucks.
[1] https://peps.python.org/pep-0380/#formal-semantics https://peps.python.org/pep-0380/#formal-semantics
[2] https://www.youtube.com/watch?v=Y4Gt3Xjd7G8 https://www.youtube.com/watch?v=Y4Gt3Xjd7G8