Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does async/await do?

I'm trying to wrap my head around async/await in python.

Am I on the right track?

  • async and @coroutine functions returns coroutine/generator, not the returned value.
  • await extracts the actual return value of coroutine/generator.
     

  • async function result (coroutines) is meant to be added to event-loop.

  • await creates "bridge" between event-loop and awaited coroutine (enabling the next point).
  • @coroutine's yield communicates directly with event-loop. (skipping direct caller which awaits the result)
     

  • await can be used only inside async functions.

  • yield can be used only inside @coroutine.

(@coroutine = @types.coroutine)

like image 394
industryworker3595112 Avatar asked Sep 22 '17 11:09

industryworker3595112


1 Answers

async and @coroutine functions returns coroutine/generator, not the returned value

To be technical, types.coroutine returns a generator-based coroutine which is different than generators and different than coroutines.

await extracts the actual return value of coroutine/generator.

await, similar to yield from, suspends the execution of the coroutine until the awaitable it takes completes and returns the result.

async function result (coroutines) is meant to be added to event-loop.

Yes.

await creates "bridge" between event-loop and awaited coroutine (enabling the next point).

await creates a suspension point that indicates to the event loop that some I/O operation will take place thereby allowing it to switch to another task.

@coroutine's yield communicates directly with event-loop. (skipping direct caller which awaits the result)

No, generator-based coroutines use yield from in a similar fashion to await, not yield.

await can be used only inside async functions.

Yes.

yield can be used only inside coroutine.

yield from can be used inside generator-based coroutines (generators decorated with types.coroutine) and, since Python 3.6, in async functions that result in an asynchronous generator.

like image 73
Dimitris Fasarakis Hilliard Avatar answered Nov 18 '22 17:11

Dimitris Fasarakis Hilliard