Coroutines: async def and await
An `async def` function defines a coroutine. Calling it returns a coroutine object instead of executing immediately. Use `await` inside coroutines to yield control back to the event loop ⏳.
import asyncio
async def fetch_user():
print("Fetching data... 📡")
await asyncio.sleep(0.01) # Yields control back to event loop!
return {"id": 101, "role": "admin"}
coro = fetch_user()
print(type(coro)) # <class 'coroutine'> ⏳
coro.close()
# 44. Coroutines: async def and await An `async def` function defines a coroutine. Calling it returns a coroutine object instead of executing immediately. Use `await` inside coroutines to yield control back to the event loop ⏳. ```python import asyncio async def fetch_user(): print("Fetching data... 📡") await asyncio.sleep(0.01) # Yields control back to event loop! return {"id": 101, "role": "admin"} coro = fetch_user() print(type(coro)) # <class 'coroutine'> ⏳ coro.close() ``` Think of `await` as a cooperative pause button. While one coroutine waits for network bytes, the event loop switches to execute other tasks on the exact same thread! ⏳ --- ### Question What does calling an `async def` function directly without `await` return? 🧠 - [ ] a. An unexecuted coroutine object ⏳ - [ ] b. The final computed return value synchronously - [ ] c. A background thread PID integer - [ ] d. A syntax error exception --- ### Challenge Define `async def ping(): return 'pong'`. Verify calling `ping()` produces a coroutine by printing `asyncio.iscoroutine(ping())`. Clean up the coroutine by closing it. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def ping(): return "pong" coro = ping() print(asyncio.iscoroutine(coro)) coro.close() ``` </details>