From baef24141a749a52596b6637b74ff205726f4e3f Mon Sep 17 00:00:00 2001 From: Timofei Ivankov <128279579+deadlovelll@users.noreply.github.com> Date: Thu, 5 Nov 2026 08:58:56 +0300 Subject: [PATCH] gh-161166: Fix incorrect exception line in asyncio.Task.print_stack() --- Lib/asyncio/base_tasks.py | 9 +++++++-- Lib/test/test_asyncio/test_tasks.py | 15 +++++++++++++++ ...2026-11-02-13-11-30.gh-issue-161166.zfFDlW.rst | 2 ++ 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-02-13-11-30.gh-issue-161166.zfFDlW.rst diff --git a/Lib/asyncio/base_tasks.py b/Lib/asyncio/base_tasks.py index c907b683413732..d588be96fb0f6e 100644 --- a/Lib/asyncio/base_tasks.py +++ b/Lib/asyncio/base_tasks.py @@ -67,10 +67,16 @@ def _task_get_stack(task, limit): def _task_print_stack(task, limit, file): + exc = task._exception + tb = exc.__traceback__ if exc is not None else None extracted_list = [] checked = set() for f in task.get_stack(limit=limit): - lineno = f.f_lineno + if tb is not None: + lineno = tb.tb_lineno + tb = tb.tb_next + else: + lineno = f.f_lineno co = f.f_code filename = co.co_filename name = co.co_name @@ -80,7 +86,6 @@ def _task_print_stack(task, limit, file): line = linecache.getline(filename, lineno, f.f_globals) extracted_list.append((filename, lineno, name, line)) - exc = task._exception if not extracted_list: print(f'No stack for {task!r}', file=file) elif exc is not None: diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py index 9b8df40ec6ece6..d6a835792681a1 100644 --- a/Lib/test/test_asyncio/test_tasks.py +++ b/Lib/test/test_asyncio/test_tasks.py @@ -335,6 +335,21 @@ async def runner(): self.loop.run_until_complete(runner()) + def test_print_stack_exception_lineno(self): + # gh-161166 + async def coro(): + try: + 1 / 0 + finally: + cleaned = True + + task = self.new_task(self.loop, coro()) + test_utils.run_briefly(self.loop) + task.exception() + file = io.StringIO() + task.print_stack(file=file) + self.assertIn(' 1 / 0\n', file.getvalue()) + def test_task_repr(self): self.loop.set_debug(False) diff --git a/Misc/NEWS.d/next/Library/2026-11-02-13-11-30.gh-issue-161166.zfFDlW.rst b/Misc/NEWS.d/next/Library/2026-11-02-13-11-30.gh-issue-161166.zfFDlW.rst new file mode 100644 index 00000000000000..4d66a399f5e655 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-02-13-11-30.gh-issue-161166.zfFDlW.rst @@ -0,0 +1,2 @@ +Fix :meth:`asyncio.Task.print_stack` displaying an incorrect exception line +after a ``finally`` block. Patch by Timofei Ivankov.