Skip to content
tezvyn:

Python Coroutines: Functions You Can Pause and Resume

Source: docs.python.orgMediumHow cards are made

Python Coroutines: Functions You Can Pause and Resume

A Python coroutine is a function that can be paused and resumed. It yields control during I/O waits, allowing other tasks to run instead of blocking the program. The main footgun: calling an async function does nothing; you must await it to run it.

Why it exists

Traditional functions block execution. If a function waits for a network request, the entire program's thread freezes. Coroutines were created to solve this for I/O-bound tasks, enabling a single thread to handle thousands of concurrent operations by interleaving them during their waiting periods.

The mental model

A coroutine is a function that can pause itself. When it hits a point where it needs to wait (e.g., for a database query), it uses the await keyword to hand control back to a central scheduler, the event loop. The event loop then runs another task that is ready to go. Once the database query is complete, the event loop will resume the original coroutine where it left off.

How it works

You define a coroutine function using async def. Calling this function, like my_coro(), does not run it. It only creates a coroutine object. This is a common source of bugs. To actually run the code, you must do one of three things: first, use asyncio.run() for the top-level entry point; second, await it from within another already-running coroutine; or third, schedule it to run concurrently using asyncio.create_task() or an asyncio.TaskGroup.

When to use it

Use coroutines for I/O-bound operations where your code spends most of its time waiting. This is ideal for building web servers, making multiple API calls, or interacting with databases and file systems. Frameworks like FastAPI and libraries like httpx are built on this principle.

When not to use it

Coroutines do not provide benefits for CPU-bound work, like complex mathematical calculations. A long-running calculation in a coroutine will still block the event loop, preventing other tasks from running. For CPU-intensive work, use multiprocessing or run the blocking function in a separate thread with asyncio.to_thread.

One canonical example

Imagine two tasks: one waits 1 second, the other waits 2. If you run them sequentially with await, the total time is 3 seconds. But if you schedule both as concurrent tasks using asyncio.create_task(), they start their timers together. The total execution time becomes just 2 seconds (the duration of the longest task), because their waiting periods overlap. This demonstrates the power of concurrent execution.

Interview question

What is the immediate result of calling a function defined with async def, like my_coro(), without awaiting it?

  • a.The function begins execution concurrently in the background, managed by the event loop.
  • b.The function's code executes immediately, blocking until completion.
  • c.A coroutine object is returned, which must be explicitly run by an event loop.Correct
  • d.An error is raised, indicating that an async function must always be awaited.
Why?

Calling an async def function directly only creates a coroutine object; it does not execute the function's code. This object must then be awaited or scheduled with an event loop to run. Option B describes synchronous function behavior, and Option A incorrectly implies immediate background execution without the necessary explicit step.

Just read this? Test yourself on what you have been reading.

Read the original → docs.python.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on python — each one lists the topics its interview covers.

See open roles