Skip to content

asyncio.shutdown_asyncgens silently drops CancelledError from generator cleanup #150866

Closed

Description

@deadlovelll

Bug report

Bug description:

asyncio.BaseEventLoop.shutdown_asyncgens silently swallows CancelledError raised during asynchronous generator cleanup:

# Lib/asyncio/base_events.py:592-599
for result, agen in zip(results, closing_agens):
    if isinstance(result, Exception):
        self.call_exception_handler({
            'message': f'an error occurred during closing of '
                        f'asynchronous generator {agen!r}',
            'exception': result,
            'asyncgen': agen
        })

CancelledError that can be raised by the aclose() is not inherited from the Exception, it inherits from BaseException.

Reproducer:

import asyncio

async def agen():
    try:
        yield 1
    finally:
        raise asyncio.CancelledError("cancelled during cleanup")

caught = []

async def main():
    loop = asyncio.get_running_loop()
    loop.set_exception_handler(lambda loop, ctx: caught.append(ctx))
    g = agen()
    await g.__anext__()
    await loop.shutdown_asyncgens()

asyncio.run(main())
assert len(caught) == 1, f"Expected 1 handler call, got {len(caught)}"

Proposed fix:

Match both Exception and CancelledError

if isinstance(result, (Exception, asyncio.CancelledError)):

CPython versions tested on:

3.16, CPython main branch

Operating systems tested on:

macOS

Linked PRs

Activity

  1. deadlovelll commented on Jun 3, 2026

    @deadlovelll
    ContributorAuthor

    I'll create the pr

  2. kumaraditya303 commented on Jul 24, 2026

    @kumaraditya303
    Contributor

    What about other base exceptions like SystemExit? I think currently they would be dropped as well.

  3. deadlovelll commented on Jul 25, 2026

    @deadlovelll
    ContributorAuthor

    What about other base exceptions like SystemExit? I think currently they would be dropped as well.

    exceptions like SystemExit do not reach this point because they reraise instead of storing it, but your direction is right, and I'll switch to isinstance(result, BaseException)

  4. added a commit that references this issue on Jul 28, 2026
  5. moved this from Todo to Done in asyncioon Jul 28, 2026
  6. added a commit that references this issue on Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-asynciotype-bugAn unexpected behavior, bug, or error

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions