This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author jnwatson
Recipients asvetlov, jnwatson, yselivanov
Date 2019-02-08.21:16:16
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1549660576.62.0.347711337086.issue35945@roundup.psfhosted.org>
In-reply-to
Content
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.
History
Date User Action Args
2019-02-08 21:16:20jnwatsonsetrecipients: + jnwatson, asvetlov, yselivanov
2019-02-08 21:16:16jnwatsonsetmessageid: <1549660576.62.0.347711337086.issue35945@roundup.psfhosted.org>
2019-02-08 21:16:16jnwatsonlinkissue35945 messages
2019-02-08 21:16:16jnwatsoncreate