[issue46771] Add some form of cancel scopes

Guido van Rossum report at bugs.python.org
Wed Feb 16 18:27:41 EST 2022


Guido van Rossum <guido at python.org> added the comment:

I hesitate to add yet another stack at this fundamental level.

The Task.cancel() method returns a bool which indicates whether any state changed.

When multiple cancellations happen concurrently, all but the first will return False, and anything that would like to cancel a task but finds that t.cancel() returns False can know that the task was either already cancelled or has already terminated. (To tell the difference, check t.done() first.)

What would be the use case of wanting to cancel multiple times and having each cancellation be delivered separately?

I know of one use case, where a task somehow decides to catch and *ignore* CancelledError (this should not be done lightly but it is supported -- like shielding in Trio). An impatient user or task manager might want to cancel such a thread a second time. This is what .uncancel() is for -- the thread must call .uncancel() to signal that it has truly ignored the cancellation (as opposed to being busy with cleanup that it deems uncancellable).

But in this case the second cancellation (if it is to have any effect) should be delivered *after* .uncancel() is called.

Your proposal of a cancel context or stack seems to be suggesting that there's a use case for mutliple *concurrent* cancellations. But I find it difficult to imagine such a use case, so I need your help.

Even if we ignore the stack idea, could you provide some code showing how the cancel context would be used? I just learn better from code examples.

----------

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


More information about the Python-bugs-list mailing list