What are coroutines, `async def` and `await`?
IntermediateConceptConcurrency: threads, processes & asyncio
Answer
async def defines a coroutine function; calling it returns a coroutine object that does nothing until awaited or scheduled. await suspends the coroutine until the awaited operation completes, letting the event loop run other coroutines meanwhile. asyncio.run(main()) creates the loop, runs main to completion and closes the loop.
import asyncio, httpx
async def main():
async with httpx.AsyncClient(timeout=5) as c:
r = await c.get("https://example.com/healthz")
print(r.status_code)
asyncio.run(main())
Forgetting await gives RuntimeWarning: coroutine '...' was never awaited and nothing happens.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedHow do you run many async tasks concurrently with a limit?Intermediate