[issue46829] Confusing CancelError message if multiple cancellations are scheduled

Chris Jerdonek report at bugs.python.org
Wed Feb 23 02:16:05 EST 2022


Chris Jerdonek <chris.jerdonek at gmail.com> added the comment:

I don't really understand all the hate around the idea of a cancel message. One reason it's useful is that it provides a simple way to say *why* something is being cancelled or *what* is cancelling it. It provides additional context to the exception, in the same way that a normal exception's message can provide additional helpful context.

Take for example this chunk of code:

import asyncio
import random

async def job():
    await asyncio.sleep(5)

async def main():
    task = asyncio.create_task(job())
    await asyncio.sleep(1)
    r = random.random()
    if r < 0.5:
        task.cancel()
    else:
        task.cancel()
    await task

if __name__=="__main__":
    asyncio.run(main())

Without passing a message, there's no way to tell which of the two lines called cancel, or why. The tracebacks are identical in both cases. This is even in the simplest case where only one cancellation is occurring. Passing a message lets one disambiguate the two call sites. And if there is truly a race condition where it's up in the air between two things cancelling it, I think it would be okay for the chosen message to be indeterminate, as either would have instigated the cancel in the absence of the other.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46829>
_______________________________________


More information about the Python-bugs-list mailing list