[Tutor] What exactly does "await" do?

David bouncingcats at gmail.com
Mon Feb 13 08:05:32 EST 2023


On Mon, 13 Feb 2023 at 21:41, Alphonsus Okoye <phonokoye at gmail.com> wrote:

> How does the await
> statement suspend the execution of a coroutine and still run the coroutine?
> I know I am missing some fundamentals here. How do I make sense of this?

Let's choose one of the coroutines you posted, as an example to discuss.
This one:

> >    async def say_after(delay, what):
> >        await asyncio.sleep(delay)
> >        print(what)

When execution reaches the 'await' statement in that coroutine,
it suspends the execution of the running coroutine named 'say_after',
and instead runs the coroutine named 'asyncio.sleep'.

That's how 'await' both suspends a coroutine (the one it is in) and runs
a coroutine (a different one that it starts).

When the coroutine named 'asyncio.sleep' returns, the coroutine
named 'say_after' will resume, from the 'print(what)' statement.

A coroutine can be recognised by having 'async def' in its
definition statement, as opposed to just 'def' for the
definition of an ordinary function or method.


More information about the Tutor mailing list