[Tutor] What exactly does "await" do? (David)
Alphonsus Okoye
phonokoye at gmail.com
Mon Feb 13 23:40:57 EST 2023
> ---------- Forwarded message ----------
> From: David <bouncingcats at gmail.com>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Tue, 14 Feb 2023 00:05:32 +1100
> Subject: Re: [Tutor] What exactly does "await" do?
> 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.
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?
I assume there is a specific problem which isn't straightforward with
normal functions. From youtube videos, the purpose of a coroutine seems to
be to execute some IO process asynchronously, but I have also read in some
stackoverflow page that a coroutine may still not execute asynchronously if
not written well. So how do I write asynchronous code using coroutines?
More specifically, if I wished to write a program that read from a long
text file "spam.txt", and while the process begins to waste time, do other
stuff like call function doOtherStuff(), what would the code look like?
More information about the Tutor
mailing list