Glossary

Coroutine

Also known as: async function

A coroutine is a function defined with async def that can be paused with await and resumed later, enabling concurrent execution without threads. When you call a coroutine function, it does not run its body; instead, it returns a coroutine object that must be awaited or scheduled on an event loop. The await keyword suspends the coroutine until the awaited operation completes, allowing other coroutines to run in the meantime.

Coroutines are the foundation of Python's asyncio framework for asynchronous programming. They are ideal for I/O-bound workloads with many concurrent connections — web servers, API clients, chat applications, web scrapers — where threads would be wasteful. A single thread running an event loop can manage thousands of concurrent coroutines.

Coroutines can call other coroutines with await, use async for to iterate over asynchronous iterators, and use async with for asynchronous context managers. The asyncio.gather() function runs multiple coroutines concurrently and collects their results. Python's coroutine model is similar to JavaScript's async/await but predates it; it evolved from generator-based coroutines (PEP 342) through native coroutines (PEP 492, Python 3.5) to the mature asyncio ecosystem available today.

Related terms: asyncio, Generator, Concurrent Futures

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.