Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generator-based coroutine versus native coroutine

I just read PEP0492 talking about the new approach on coroutines but the PEP failed to make me understand the difference between generator-based coroutines and native ones. Can someone tell me the difference (maybe with examples)?

For what I understood they uses different words (yield/yield from and await/async/yield). I understand that at the end of a native coroutine a yield is expected, but this also stands true for generator-based ones.

like image 556
Koldar Avatar asked Sep 15 '15 09:09

Koldar


2 Answers

To expand on what Mike S wrote: native coroutines in CPython share most of the same code as generators, so there's little functional difference. However, I think that PEP-492 rises above the threshold of just "syntactic sugar". Generators and native coroutines have separate purposes, so the new syntax clarifies an author's intent and can do things the old syntax cannot. Here are some examples:

  • Generators are iterable, and native coroutines are not.
  • Native coroutines also permit new syntaxes like async context managers and async iterators.
  • Coroutines have useful debugging messages, e.g. a warning if you never await a coroutine object.

The new syntax also nicely mirrors the asyncio library and resembles keywords used in other languages.

like image 133
Mark E. Haase Avatar answered Oct 01 '22 04:10

Mark E. Haase


There is no functional difference. "Native coroutines" using the async and await keywords are just syntactic sugar for what was previously implemented in "generator-based coroutines."

The use of async and await is recommended in the 3.5 docs if there is no need to support older Python versions.

like image 26
Mike S Avatar answered Oct 01 '22 06:10

Mike S