From 3dc7c52a9f4fb83be3e26e31e2c7cd9dc1cb41a2 Mon Sep 17 00:00:00 2001 From: INADA Naoki Date: Thu, 11 May 2017 21:56:42 +0900 Subject: bpo-30048: asyncio: fix Task.cancel() was ignored. (GH-1546) when there are no more `await` or `yield (from)` before return in coroutine, cancel was ignored. example: async def coro(): asyncio.Task.current_task().cancel() return 42 ... res = await coro() # should raise CancelledError (cherry picked from commit 991adca012f5e106c2d4040ce619c696ba6f9c46) --- Lib/asyncio/tasks.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'Lib/asyncio/tasks.py') diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index f91e70aecb..d7867d128a 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -180,7 +180,12 @@ class Task(futures.Future): else: result = coro.throw(exc) except StopIteration as exc: - self.set_result(exc.value) + if self._must_cancel: + # Task is cancelled right before coro stops. + self._must_cancel = False + self.set_exception(futures.CancelledError()) + else: + self.set_result(exc.value) except futures.CancelledError: super().cancel() # I.e., Future.cancel(self). except Exception as exc: -- cgit v1.2.1