diff --git a/Lib/asyncio/graph.py b/Lib/asyncio/graph.py index d76d2f6383343d5..72800f667996446 100644 --- a/Lib/asyncio/graph.py +++ b/Lib/asyncio/graph.py @@ -51,7 +51,7 @@ def _build_graph_for_future( coro = None if get_coro := getattr(future, 'get_coro', None): - coro = get_coro() if limit != 0 else None + coro = get_coro() if limit != 0 and not future.done() else None st: list[FrameCallGraphEntry] = [] awaited_by: list[FutureCallGraph] = [] diff --git a/Lib/test/test_asyncio/test_graph.py b/Lib/test/test_asyncio/test_graph.py index 1f1c76e4aef69f8..22f13a9cb47ba34 100644 --- a/Lib/test/test_asyncio/test_graph.py +++ b/Lib/test/test_asyncio/test_graph.py @@ -866,6 +866,28 @@ async def boom(): self.assertEqual(asyncio.capture_call_graph(task).call_stack, ()) self.assertIn(f"name={task.get_name()!r}", buf.getvalue()) + async def test_call_graph_finished_anext_task(self): + # gh-162235 + async def gen(): + yield 1 + await asyncio.sleep(0) + yield 2 + + agen = gen() + done = asyncio.create_task(anext(agen), name='done') + await done + + other = asyncio.create_task(anext(agen), name='other') + await asyncio.sleep(0) + done_graph = asyncio.capture_call_graph(done) + + await other + await agen.aclose() + other_graph = asyncio.capture_call_graph(other) + + self.assertEqual(done_graph.call_stack, ()) + self.assertEqual(other_graph.call_stack, ()) + async def test_capture_call_graph_no_current_task(self): results = [] diff --git a/Misc/NEWS.d/next/Library/2026-11-18-23-23-57.gh-issue-162235.h69wQX.rst b/Misc/NEWS.d/next/Library/2026-11-18-23-23-57.gh-issue-162235.h69wQX.rst new file mode 100644 index 000000000000000..2da4d569767ef33 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-18-23-23-57.gh-issue-162235.h69wQX.rst @@ -0,0 +1,3 @@ +Fix :func:`asyncio.print_call_graph` showing incorrect stacks or raising +:exc:`AttributeError` for finished :func:`anext` tasks. Patch by Timofey +Ivankov.