from asyncio import CancelledError, coroutine, ensure_future, gather, get_event_loop, sleep tasks = [] def cancel_task(_): print('Cancelling the task:', tasks[0]) print('Cancellation returned: ', tasks[0].cancel()) @coroutine def gather_test(): task = ensure_future(sleep(0.1)) # cancel_task is only added as a callback here since it guarantees # delivery of the cancellation at the 'unfortunate' time that # triggers the bug. It can also occur if cancellation is triggered # otherwise. However, that is very hard to set up for a test case. task.add_done_callback(cancel_task) yield from gather(task) print('Finished gathering.') yield from sleep(1) print('Proof that this is running even though it was cancelled') @coroutine def main(): try: tasks.append(ensure_future(gather_test())) yield from tasks[0] except CancelledError: print('CancelledError in main()') yield from sleep(2) get_event_loop().run_until_complete(main())