Python
Advanced
What is Python Coroutine?
A function defined with async def that can be paused and resumed, enabling concurrent execution without threads.
Coroutines are the foundation of Python's asyncio framework. Defined with async def, they use await to suspend execution while waiting for I/O operations (network requests, file reads, database queries). The event loop manages multiple coroutines, switching between them when one awaits. This achieves concurrency without thread overhead or the complexity of multiprocessing. Coroutines are not parallel — they run on a single thread but overlap waiting time efficiently. Key patterns include async for (async iteration), async with (async context managers), and asyncio.gather() for running multiple coroutines concurrently.