Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

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.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio