Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.8 — Async Iterators, Generators and Context Managers
Python · Example 3 of 3

Producer, queue and workers

The queue holds two items, so the producer is slowed down by the workers (back-pressure). Results are sorted because workers finish in no fixed order.

async for loops over values that arrive over time, an async generator (async def with yield) produces them, async with opens and closes resources that need to await, and asyncio.Queue passes work between tasks. Streaming model tokens is the classic use.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write an async generator countdown(n) that yields n, n-1, ... 1 with await asyncio.sleep(0.01) before each, and print the values joined by spaces.

02

Write an async generator take(stream, k) that yields at most the first k items of another async stream. Use it on countdown(10) with k=3.

03

Write an async context manager timer_label(name) with @asynccontextmanager that prints start <name> and end <name> around a block.

Explain it without notes

01

What is the difference between a normal generator and an async generator? When do you need the async one?

02

What does async with do that with cannot, and how can you write your own async context manager?

03

Why is closing an async generator after break important in streaming code?

04

How does a bounded asyncio.Queue create back-pressure, and why is task_done called in finally?

05

You have two async streams (say two model endpoints) and want to handle items from whichever produces first. A plain async for over one then the other does not do that. How do you do it?

Producer, queue and workers
Sign in to run this example in your browser.

Expected output

['prompt 0 -> done', 'prompt 1 -> done', 'prompt 2 -> done', 'prompt 3 -> done', 'prompt 4 -> done', 'prompt 5 -> done']
queue empty: True