Skip to content

Commit 7d611b4

Browse files
authored
bpo-46771: Remove two controversial lines from Task.cancel() (GH-31623)
Also from the _asyncio C accelerator module, and adjust one test that the change caused to fail. For more discussion see the discussion starting here: #31394 (comment) (Basically, @asvetlov proposed to return False from cancel() when there is already a pending cancellation, and I went along, even though it wasn't necessary for the task group implementation, and @agronholm has come up with a counterexample that fails because of this change. So now I'm changing it back to the old semantics (but still bumping the counter) until we can have a proper discussion about this.)
1 parent 08deed1 commit 7d611b4

File tree

3 files changed

+17
-6
lines changed

3 files changed

+17
-6
lines changed

Lib/asyncio/tasks.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -205,8 +205,11 @@ def cancel(self, msg=None):
205205
if self.done():
206206
return False
207207
self._num_cancels_requested += 1
208-
if self._num_cancels_requested > 1:
209-
return False
208+
# These two lines are controversial. See discussion starting at
209+
# https://github.com/python/cpython/pull/31394#issuecomment-1053545331
210+
# Also remember that this is duplicated in _asynciomodule.c.
211+
# if self._num_cancels_requested > 1:
212+
# return False
210213
if self._fut_waiter is not None:
211214
if self._fut_waiter.cancel(msg=msg):
212215
# Leave self._fut_waiter; it may be a Task that

Lib/test/test_asyncio/test_tasks.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,11 @@ async def task():
514514
self.assertTrue(t.cancel())
515515
self.assertTrue(t.cancelling())
516516
self.assertIn(" cancelling ", repr(t))
517-
self.assertFalse(t.cancel())
517+
518+
# Since we commented out two lines from Task.cancel(),
519+
# this t.cancel() call now returns True.
520+
# self.assertFalse(t.cancel())
521+
self.assertTrue(t.cancel())
518522

519523
with self.assertRaises(asyncio.CancelledError):
520524
loop.run_until_complete(t)

Modules/_asynciomodule.c

+7-3
Original file line numberDiff line numberDiff line change
@@ -2206,9 +2206,13 @@ _asyncio_Task_cancel_impl(TaskObj *self, PyObject *msg)
22062206
}
22072207

22082208
self->task_num_cancels_requested += 1;
2209-
if (self->task_num_cancels_requested > 1) {
2210-
Py_RETURN_FALSE;
2211-
}
2209+
2210+
// These three lines are controversial. See discussion starting at
2211+
// https://github.com/python/cpython/pull/31394#issuecomment-1053545331
2212+
// and corresponding code in tasks.py.
2213+
// if (self->task_num_cancels_requested > 1) {
2214+
// Py_RETURN_FALSE;
2215+
// }
22122216

22132217
if (self->task_fut_waiter) {
22142218
PyObject *res;

0 commit comments

Comments
 (0)