New submission from Nic Watson <pythonb...@nicwatson.org>:
Goal: to distinguish inside a CancelledError exception handler whether the current running task is being cancelled, or another task that the current task is pending on was cancelled. Example: import asyncio async def task2func(): await asyncio.sleep(2) async def task1func(task2): try: await task2 except asyncio.CancelledError: print("I don't know if I got cancelled") async def main(): loop = asyncio.get_event_loop() task2 = loop.create_task(task2func()) task1 = loop.create_task(task1func(task2)) await asyncio.sleep(0.5) print('Cancelling first task') task1.cancel() await task1 await asyncio.sleep(0.5) task2 = loop.create_task(task2func()) task1 = loop.create_task(task1func(task2)) await asyncio.sleep(0.5) print('Cancelling second task') task2.cancel() await task1 asyncio.run(main()) If I have a task1 waiting on a task2, there's no public method (that I can tell) available in the task1func exception handler to distinguish between whether task1 or task2 were cancelled. There is an internal field task_must_cancel in the C task struct that could be used to interrogate one's own current task to see if it is being cancelled. It is not available from Python (without ctypes hacking). The Python implementation's equivalent is called _must_cancel. (I'm not sure it is a good idea to export this from an API design perspective, but it does mean a mechanism exists.) A workaround is that one can explicitly add attributes to the Python task object to communicate that a task is *starting to* be cancelled. This field would have the same purpose as the task_must_cancel field. ---------- components: asyncio messages: 335108 nosy: asvetlov, jnwatson, yselivanov priority: normal severity: normal status: open title: Cannot distinguish between subtask cancellation and running task cancellation versions: Python 3.7 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue35945> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com