Coroutines and await
async def creates a coroutine function
Section titled “async def creates a coroutine function”import asyncio
async def say_hi():
await asyncio.sleep(0.1)
return "hi"Calling vs awaiting
Section titled “Calling vs awaiting”Calling a coroutine function returns a coroutine object.
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
Section titled “await points”You can only use await inside an async def function.
If you need to run async code from normal code, use:
asyncio.run(main())(most common)
Common mistake
Section titled “Common mistake”This does nothing useful:
async def main():
say_hi() # forgot awaitBecause the coroutine is created but never awaited.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Your First Coroutine
Section titled “Exercise 1 – Your First Coroutine”Exercise 2 – await asyncio.sleep
Section titled “Exercise 2 – await asyncio.sleep”Exercise 3 – Gather Two Coroutines
Section titled “Exercise 3 – Gather Two Coroutines”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading