Functions and coroutines#
import asyncio
import time
A traditional function definition as def shows.
Calling it runs the function
def blocking_wait_for(wait_for):
time.sleep(wait_for)
print(f"Done waiting for {wait_for} seconds.")
return wait_for
result = blocking_wait_for(1)
print(result)
Done waiting for 1 seconds.
1
Another function.
async def indicates we implement asynchronous functionality.
Calling it generates a coroutine.
It’s not executed yet!
The await statement makes it interruptible.
async def friendly_wait_for(wait_for):
await asyncio.sleep(wait_for)
print(f"Done waiting for {wait_for} seconds.")
return wait_for
coro = friendly_wait_for(1)
coro
<coroutine object friendly_wait_for at 0x108d582b0>
awaiting the coroutine triggers execution.
Once execution is finished the result is returned.
result = await coro
print(result)
Done waiting for 1 seconds.
1