Message 336009 - Python tracker (original) (raw)
There's no clear reason to complicate the Task<->coroutine relationship by allowing to inject arbitrary exceptions into running coroutines.
My comment was more about CancelledError rather than arbitrary exceptions. You didn't reply to the part of my response saying that Task.cancel() doesn't let you communicate why the task was ended, [..]
I didn't reply because you didn't clearly articulate why the cancellation reason is important :) AFAIK no other async framework allows you to do this. So what are those real-world cases that can explain why asyncio should support this functionality?
[..] which is something the removed API's let you do.
Unfortunately they didn't. They never worked properly; IIRC Task.set_exception had never worked at all. The fact they were available at all was a simple oversight.
Task.set_exception() and Task.set_result() both give you a way to unconditionally end a task. With cancel() though, the docs say, "Task.cancel() does not guarantee that the Task will be cancelled." [1]
Yes, because Task can only signal its coroutine that it was requested to be cancelled. The coroutine may choose to ignore that by swallowing CancelledError.
The reason you might want to unconditionally end a task is if e.g. you already called Task.cancel() and it is still running after waiting a certain amount of time.
Well, if you want to unconditionally end tasks you shouldn't write coroutines that ignore CancelledErrors. If you do, then you clearly do not want the coroutine to be cancelled, and thus there's no use case for set_exception.
Finally, asyncio has queues, which can be used to build two-way communication channels between coroutines and implement whatever advanced cancellation mechanism you want.