Skip to content

Commit 6f2c029

Browse files
committed
gh-161166: Fix incorrect exception line in asyncio.Task.print_stack()
1 parent 5172ac9 commit 6f2c029

3 files changed

Lines changed: 26 additions & 2 deletions

File tree

‎Lib/asyncio/base_tasks.py‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,10 +67,18 @@ def _task_get_stack(task, limit):
6767

6868

6969
def _task_print_stack(task, limit, file):
70+
# gh-161166: use the traceback line number instead of the frame’s current line number
71+
# because it can give false exception causes
72+
exc = task._exception
73+
tb = exc.__traceback__ if exc is not None else None
7074
extracted_list = []
7175
checked = set()
7276
for f in task.get_stack(limit=limit):
73-
lineno = f.f_lineno
77+
if tb is not None:
78+
lineno = tb.tb_lineno
79+
tb = tb.tb_next
80+
else:
81+
lineno = f.f_lineno
7482
co = f.f_code
7583
filename = co.co_filename
7684
name = co.co_name
@@ -80,7 +88,6 @@ def _task_print_stack(task, limit, file):
8088
line = linecache.getline(filename, lineno, f.f_globals)
8189
extracted_list.append((filename, lineno, name, line))
8290

83-
exc = task._exception
8491
if not extracted_list:
8592
print(f'No stack for {task!r}', file=file)
8693
elif exc is not None:

‎Lib/test/test_asyncio/test_tasks.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,21 @@ async def runner():
335335

336336
self.loop.run_until_complete(runner())
337337

338+
def test_print_stack_exception_lineno(self):
339+
# gh-161166
340+
async def coro():
341+
try:
342+
1 / 0
343+
finally:
344+
cleaned = True
345+
346+
task = self.new_task(self.loop, coro())
347+
test_utils.run_briefly(self.loop)
348+
task.exception()
349+
file = io.StringIO()
350+
task.print_stack(file=file)
351+
self.assertIn(' 1 / 0\n', file.getvalue())
352+
338353
def test_task_repr(self):
339354
self.loop.set_debug(False)
340355

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :meth:asyncio.Task.print_stack displaying an incorrect exception line
2+
after a finally block. Patch by Timofei Ivankov.

0 commit comments

Comments
 (0)