Skip to content

Commit 1cc94c9

Browse files
committed
bpo-30048: asyncio: fix Task.cancel() was ignored.
example: async def coro(): asyncio.Task.current_task().cancel() return 42 ... res = await coro() # should raise CancelledError
1 parent f77d887 commit 1cc94c9

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

Lib/asyncio/tasks.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,12 @@ def _step(self, exc=None):
180180
else:
181181
result = coro.throw(exc)
182182
except StopIteration as exc:
183-
self.set_result(exc.value)
183+
if self._must_cancel:
184+
# Task is cancelled right before coro stops.
185+
self._must_cancel = False
186+
self.set_exception(futures.CancelledError())
187+
else:
188+
self.set_result(exc.value)
184189
except futures.CancelledError:
185190
super().cancel() # I.e., Future.cancel(self).
186191
except Exception as exc:

Modules/_asynciomodule.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1985,6 +1985,16 @@ task_step_impl(TaskObj *task, PyObject *exc)
19851985
if (_PyGen_FetchStopIterationValue(&o) == 0) {
19861986
/* The error is StopIteration and that means that
19871987
the underlying coroutine has resolved */
1988+
if (task->task_must_cancel) {
1989+
// Task is cancelled right before coro stops.
1990+
Py_DECREF(o);
1991+
task->task_must_cancel = 0;
1992+
et = asyncio_CancelledError;
1993+
Py_INCREF(et);
1994+
ev = NULL;
1995+
tb = NULL;
1996+
goto set_exception;
1997+
}
19881998
PyObject *res = future_set_result((FutureObj*)task, o);
19891999
Py_DECREF(o);
19902000
if (res == NULL) {
@@ -2002,6 +2012,8 @@ task_step_impl(TaskObj *task, PyObject *exc)
20022012

20032013
/* Some other exception; pop it and call Task.set_exception() */
20042014
PyErr_Fetch(&et, &ev, &tb);
2015+
2016+
set_exception:
20052017
assert(et);
20062018
if (!ev || !PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
20072019
PyErr_NormalizeException(&et, &ev, &tb);

0 commit comments

Comments
 (0)