🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Async Generators, TaskGroups, and Async Context Managers

Python AsyncAsync PatternsđŸŸĸ Free Lesson

Async Generators, TaskGroups, and Async Context Managers

Asyncio code is easy to write and hard to trust. The happy path — create tasks, gather results, print them — fits in ten lines and demos beautifully. Production adds the questions that break naive code: what happens to an open connection when the task is cancelled mid-query, how do you bound concurrency so you do not open four thousand sockets at once, and how do you make sure one failing task takes its siblings down instead of leaving orphan work running. The tools for those questions exist in the standard library: async generators, async context managers, TaskGroup, and Semaphore.

This lesson treats them as a set rather than as separate features, because their value comes from how they compose — cleanup that runs on cancellation, bounded fan-out that propagates failure, and streams that close their own resources.


The contract the loop expects

Everything below rests on three rules. A coroutine that never awaits can still block the loop, so CPU work must move to a thread or process pool. Any library that talks to the network must offer an async interface, or every call becomes a stall. And cancellation is cooperative: a cancelled task gets an exception thrown at its current await point, and it must be allowed to reach its cleanup code — which is precisely why async context managers and finally blocks matter so much.

python
import asyncio

async def fetch_all(urls, limit=20):
    semaphore = asyncio.Semaphore(limit)

    async def bounded(url):
        async with semaphore:                # at most 20 requests in flight
            return await http_get(url)

    return await asyncio.gather(*(bounded(u) for u in urls))

The semaphore is the smallest possible answer to the fan-out problem, and putting it inside a helper coroutine rather than around the gather is what makes the limit apply per request rather than per batch.

Async generators for streams you do not buffer

An async generator yields values as they become available, which is the right shape for paginated APIs, tailing a log, or reading a socket — cases where the whole point is that you must not wait for everything before starting. The async for loop that consumes it is the mirror image: it awaits each item and releases the loop between them.

python
import aiofiles

async def read_lines(path, chunk_delay=0.0):
    """Yield non-empty lines without ever holding the file in memory."""
    async with aiofiles.open(path, encoding="utf-8") as fh:
        async for line in fh:
            line = line.strip()
            if not line:
                continue
            if chunk_delay:
                await asyncio.sleep(chunk_delay)
            yield line

async def tail(path, stop_event):
    last_size = 0
    while not stop_event.is_set():
        size = (await aiofiles.os.stat(path)).st_size
        if size > last_size:
            async for line in read_lines(path):
                if line:
                    yield line
            last_size = size
        await asyncio.sleep(0.5)

Two properties make async generators worth the syntax. Laziness is guaranteed — nothing is read until the consumer asks — and cleanup is guaranteed too: when the loop exits or the consuming task is cancelled, Python raises GeneratorExit into the generator at its current yield, and any async with or finally inside runs. That is the same discipline as a synchronous generator, with the added requirement that cleanup code that touches I/O must itself be awaited.

Async context managers: cleanup that survives cancellation

An async context manager is the only reliable place to hold a resource that needs closing, because it runs its exit path no matter how the block ends — normally, by exception, or by cancellation. contextlib.asynccontextmanager gives you the familiar try/finally shape in an async with wrapper.

python
from contextlib import asynccontextmanager

@asynccontextmanager
async def db_connection(dsn, timeout=10.0):
    conn = await asyncpg.connect(dsn, timeout=timeout)
    try:
        yield conn
    except asyncio.CancelledError:
        logging.warning("connection work cancelled — rolling back")
        await conn.execute("ROLLBACK")
        raise
    finally:
        await conn.close()

async def transfer(uow):
    async with db_connection(DSN) as conn:
        async with conn.transaction():
            await conn.execute("UPDATE accounts SET balance = balance - $1 WHERE id = 1", 50)
            await conn.execute("UPDATE accounts SET balance = balance + $1 WHERE id = 2", 50)

The explicit CancelledError branch is deliberate. If you swallow the cancellation, the task keeps running after its owner has given up on it; if you let it propagate after rolling back, the transaction is closed and the loop's bookkeeping stays correct.

TaskGroup: failure becomes structured

Before TaskGroup (Python 3.11), a fan-out used gather and the failure semantics were easy to get wrong: by default, one exception left the other tasks running, and their results were abandoned. TaskGroup makes the group the unit of lifetime — when any task raises, the group cancels its siblings, waits for them to clean up, and re-raises as an ExceptionGroup.

python
import asyncio

async def main():
    async with asyncio.TaskGroup() as tg:
        task_a = tg.create_task(worker("orders"))
        task_b = tg.create_task(worker("invoices"))
        task_c = tg.create_task(worker("stock"))

    # reached only if every task succeeded
    return task_a.result(), task_b.result(), task_c.result()

async def worker(name):
    try:
        return await fetch_metrics(name)
    except asyncio.CancelledError:
        logging.info("%s cancelled cleanly", name)
        raise

The block-exit semantics are the feature: control leaves the async with only when every child has finished, so there is no window in which results are half-collected. For code that must tolerate individual failures, catch inside the worker rather than letting the exception reach the group — the group is for "all of these must succeed".

Timeouts and cancellation as control flow

A timeout is not an error to log; it is a decision to stop waiting. asyncio.timeout (3.11+) scopes that decision to a block, raises TimeoutError into the slow task at its current await, and gives you a single place to decide whether to retry, degrade, or give up.

python
import asyncio

async def call_with_budget(url, budget=5.0, retries=2):
    last = None
    for attempt in range(retries + 1):
        try:
            async with asyncio.timeout(budget):
                return await http_get(url)
        except TimeoutError as exc:
            last = exc
            logging.warning("timeout %d/%d on %s", attempt + 1, retries + 1, url)
            await asyncio.sleep(0.5 * 2 ** attempt)     # backoff, still async
    raise DependencyUnavailable(f"{url} exceeded budget") from last

Because the timeout wraps only the call, backoff sleeps outside it stay cheap, and a retry does not inherit the previous attempt's remaining budget. That separation — budget around the I/O, policy around the retries — is the pattern that keeps timeouts from turning into silent data loss.

Patterns side by side

ProblemToolFailure behaviour
Bound concurrent requestsSemaphoreWaiters queue; no limit breach
Fan-out that must all succeedTaskGroupCancels siblings, raises group error
Fan-out tolerating partial failuregather(..., return_exceptions=True)Collects errors as values
Deadline around one callasyncio.timeoutCancels the call at the await point
Stream results without bufferingasync generatorCleanup runs at GeneratorExit
Hold a connection safelyasync context managerExit path runs on cancel too
CPU-heavy step inside async codeasyncio.to_threadKeeps the loop responsive

How async bugs present themselves

Async failures have distinctive signatures, which makes them diagnosable once you know the vocabulary. A hang with no output usually means a task was created but never awaited, or a gather is waiting on a coroutine that itself waits on the gather. A task that ignores Ctrl-C typically swallowed CancelledError in an over-broad except Exception. Corrupted state after a cancel points to a finally that awaited nothing, so cleanup raced with the loop's shutdown. And a sudden flood of concurrent requests almost always means a semaphore was created inside the loop that needed it, giving every call its own.

Log task names and use asyncio.all_tasks() in your health endpoint; knowing what is live at the moment of a stall is half the debugging already done.

A complementary habit is to keep the async surface of a module small. Code that is entirely synchronous can be called from an async program by wrapping it in asyncio.to_thread, but code that is partly async — a function that sometimes awaits and sometimes does not — forces every caller to reason about which case they are in. Make a module's public functions either plainly synchronous or plainly asynchronous, document which, and the boundary between the two worlds stays somewhere you chose rather than somewhere it drifted.

Common Mistakes

Catching Exception broadly and swallowing CancelledError

Fix: Re-raise CancelledError after cleanup so the loop's bookkeeping stays correct

Using gather and assuming a failure stops the other tasks

Fix: Use TaskGroup for all-must-succeed fan-out, or return_exceptions for partial tolerance

Doing CPU work directly inside a coroutine

Fix: Move it to asyncio.to_thread or a process pool so the loop stays responsive

Creating a semaphore per request instead of sharing one

Fix: Build the semaphore once per loop and share it across all bounded calls

Forgetting that async generators must await their own cleanup

Fix: Use async with inside the generator so close and cancel still release resources

Best Practices

  • Wrap every resource that needs closing in an async context manager
  • Scope deadlines with asyncio.timeout around the I/O, not around the retry loop
  • Prefer TaskGroup when siblings should die together; gather only when they should not
  • Give tasks descriptive names so all_tasks() output is readable during an incident
  • Assert in shutdown paths that every task finished or was cancelled deliberately

Key Takeaways

  • Cancellation is cooperative and arrives at an await point — cleanup must be awaitable
  • Async generators stream lazily and still get their exit path run at GeneratorExit
  • TaskGroup gives structured concurrency: all children done before the block exits
  • Semaphores bound fan-out; timeouts bound waiting; both are policy, not error handling
  • Async bugs have recognisable shapes — unawaited tasks, swallowed cancels, per-call semaphores
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement