Skip to content

Commit 4b7b581

Browse files
authored
gh-161166: Fix incorrect exception line in asyncio.Task.print_stack() (#161167)
1 parent 7c5231e commit 4b7b581

3 files changed

Lines changed: 24 additions & 2 deletions

File tree

‎Lib/asyncio/base_tasks.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,16 @@ def _task_get_stack(task, limit):
7070

7171

7272
def _task_print_stack(task, limit, file):
73+
exc = task._exception
74+
tb = exc.__traceback__ if exc is not None else None
7375
extracted_list = []
7476
checked = set()
7577
for f in task.get_stack(limit=limit):
76-
lineno = f.f_lineno
78+
if tb is not None:
79+
lineno = tb.tb_lineno
80+
tb = tb.tb_next
81+
else:
82+
lineno = f.f_lineno
7783
co = f.f_code
7884
filename = co.co_filename
7985
name = co.co_name
@@ -83,7 +89,6 @@ def _task_print_stack(task, limit, file):
8389
line = linecache.getline(filename, lineno, f.f_globals)
8490
extracted_list.append((filename, lineno, name, line))
8591

86-
exc = task._exception
8792
if not extracted_list:
8893
print(f'No stack for {task!r}', file=file)
8994
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_get_stack_async_generator(self):
339354
# gh-161178
340355
async def gen():
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)