[Tutor] What exactly does "await" do? (David)
Mats Wichmann
mats at wichmann.us
Tue Feb 14 11:37:16 EST 2023
On 2/13/23 21:40, Alphonsus Okoye wrote:
>> ---------- Forwarded message ----------
> Good day Mr David and to everyone here. From what you said, the coroutine
> can be executed just like a function; the execution of the main function is
> suspended till the inner function has finished executing. What is then the
> main purpose of a coroutine?
Wouldn't express it quite this way. In an async program, you have a
main part of the program that keeps running - usually called an event
loop. It decides if there's any work that can be done, in the form of
resuming things that are now ready. The await keyword is you telling
Python that this is a point where it's okay to stash the current state
and go off and do other work. So if you fired off a request to a
webserver, which is "slow" in terms of computer time, and you flag with
await that it's okay not to stall execution until it responds, then the
main loop picks back up and figures out if there's other work that can
be done. At some point later, the main loop will spot that the thing
being awaited is done, and it can restart execution with that saved
context. The restarted code then has to give up control again so the
main loop can continue - either by returning from the function, or
another await. And so on.
A coroutine is just a function that is able to be suspended/restarted,
which you flag to Python by using the async keyword - you have to have
indicated that it's a coroutine to be allowed to use await in it. The
async/await syntax was the approach chosen to retrofit async
capabilities into an already mature language without breaking the
behavior of tons of existing code which does not use async principles
(and doesn't need to).
More information about the Tutor
mailing list