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

Coroutines vs Functions vs Generators

Stryg for at vise menuen

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ælg det korrekte svar

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 6

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 6
some-alt