[Tutor] What exactly does "await" do?
Alphonsus Okoye
phonokoye at gmail.com
Mon Feb 13 02:10:16 EST 2023
Given below is a part of the python offline doc 3.10: Language reference,
section 6.4
> Suspend the execution of coroutine on an awaitable object. Can only be
> used inside a coroutine function.
> *await_expr* ::= "await" primary
> New in version 3.5.
Here is another part of the same doc on "Coroutines and tasks"
> To actually run a coroutine, asyncio provides three main mechanisms:
>
> -
>
> Awaiting on a coroutine. The following snippet of code will print
> “hello” after waiting for 1 second, and then print “world” after waiting
> for *another* 2 seconds:
>
> import asyncioimport time
> async def say_after(delay, what):
> await asyncio.sleep(delay)
> print(what)
> async def main():
> print(f"started at {time.strftime('%X')}")
>
> await say_after(1, 'hello')
> await say_after(2, 'world')
>
> print(f"finished at {time.strftime('%X')}")
> asyncio.run(main()) ...
>
>
> Aren't those two statements contradictory? 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?
More information about the Tutor
mailing list