2

Python 3.5 with PEP 492 introduces special syntax for coroutines and awaitables and illustrates the await keyword as follows:

The following new await expression is used to obtain a result of coroutine execution:

async def read_data(db):
    data = await db.fetch('SELECT ...')
    ...

await, similarly to yield from, suspends execution of read_data coroutine until db.fetch awaitable completes and returns the result data.

It continues to define that awaitables can be coroutines or Future-like objects, with a specific definition of Future-like objects. But despite reading the PEP, I don't quite understand what's special about await. In the line quoted from the PEP above, who returns the result data — await or read_data (or both)? Surely no matter how I call db.fetch('SELECT ...') (directly, with yield from, or with await), read_data will not continue until it gets something (possibly None) from db.fetch? Then what's special about await and how is it related to async?

Clearly I'm missing something.

gerrit
  • 24,025
  • 17
  • 97
  • 170
  • Huh, that question wasn't there when I started writing mine... – gerrit Jul 08 '15 at 12:00
  • 1
    `yield from` *delegates* to another generator. If that other generator just yields *I'm not ready* signals, an event handler can move on to iterating over another generator. Co-routines formalise that behaviour; `await` passes on the *I'm not ready* signal, or executes the inner-most co-routine if it is actually ready to do something. – Martijn Pieters Jul 08 '15 at 12:00
  • Nope, the two of you coincided quite closely in asking your questions. – Martijn Pieters Jul 08 '15 at 12:00
  • 1
    `await` will suspend execution of `read_data` until the results are actually ready. In this context, "suspending execution" means that control will be returned to an event loop, which will continue to run other callbacks (or wait for something interesting to happen). Once database results are ready, `await` will make sure that the data (as opposed to a "Future" object) is returned. – user4815162342 Jul 08 '15 at 12:26

0 Answers0