Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Coroutines vs Functions vs Generators | The Asyncio Foundation
Python Asyncio in Depth

Coroutines vs Functions vs Generators

Svep för att visa menyn

Python has three types of callable objects that can produce values and be paused mid-execution. Understanding their differences prevents confusion when reading async code and helps you choose the right tool.

Regular Functions

A regular function runs from start to finish in one go. It blocks the caller until it returns.

123456
# Returning a post title synchronously def get_post_title(post_id): return f"Post number {post_id}" title = get_post_title(1) print(title) # Post number 1
  • Called with ();
  • Runs completely before returning control;
  • Cannot be paused or resumed.

Generators

A generator function uses yield to produce values one at a time. It pauses at each yield and resumes when next() is called.

12345678910
# Generating post IDs one at a time def post_id_generator(count): for post_id in range(1, count + 1): yield post_id # Pausing here, resuming on next() generator = post_id_generator(3) print(next(generator)) # 1 print(next(generator)) # 2 print(next(generator)) # 3

Generators are about lazy value production – they don't compute all values upfront.

Coroutines

A coroutine is defined with async def and uses await to pause execution. Unlike generators, coroutines pause to wait for I/O – not to produce values.

12345678910111213141516
import asyncio import httpx import nest_asyncio nest_asyncio.apply() # Fetching a post and pausing while waiting for the response async def fetch_post(post_id): async with httpx.AsyncClient() as client: response = await client.get( f"https://jsonplaceholder.typicode.com/posts/{post_id}" ) data = response.json() return data["title"] asyncio.run(fetch_post(1))

Coroutines are about cooperative scheduling – yielding control to the event loop while waiting.

Side-by-Side Comparison

The Key Distinction

Generators and coroutines both pause execution, but for different reasons:

  • A generator pauses to hand a value to the caller;
  • A coroutine pauses to wait for an external operation and let other coroutines run.

Internally, coroutines are built on top of Python's generator protocol – which is why the syntax looks similar. But at the usage level, they serve entirely different purposes.

question mark

What is the key difference between a generator and a coroutine?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 6

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 6
some-alt