Coroutines and await
async def creates a coroutine function
coroutine_def.py
import asyncio
async def say_hi():
await asyncio.sleep(0.1)
return "hi"coroutine_def.py
import asyncio
async def say_hi():
await asyncio.sleep(0.1)
return "hi"Calling vs awaiting
Calling a coroutine function returns a coroutine object.
calling_vs_awaiting.py
import asyncio
async def say_hi():
await asyncio.sleep(0.1)
return "hi"
async def main():
c = say_hi() # coroutine object (NOT executed yet)
msg = await say_hi() # executed
print(type(c))
print(msg)
asyncio.run(main())calling_vs_awaiting.py
import asyncio
async def say_hi():
await asyncio.sleep(0.1)
return "hi"
async def main():
c = say_hi() # coroutine object (NOT executed yet)
msg = await say_hi() # executed
print(type(c))
print(msg)
asyncio.run(main())await points
You can only use awaitawait inside an async defasync def function.
If you need to run async code from normal code, use:
asyncio.run(main())asyncio.run(main())(most common)
Common mistake
This does nothing useful:
wrong.py
async def main():
say_hi() # forgot awaitwrong.py
async def main():
say_hi() # forgot awaitBecause the coroutine is created but never awaited.
๐งช Try It Yourself
Exercise 1 โ Your First Coroutine
Exercise 2 โ await asyncio.sleep
Exercise 3 โ Gather Two Coroutines
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
