wemake-services/wemake-python-styleguide

Disallow suppressing CancelledError

Dreamsorcerer opened this issue · 0 comments

Rule request

Disallow suppressing a CancelledError in most cases.

i.e.

try:
    ...
except asyncio.CancelledError:
    ...  # Code without an unconditional (re-)raise.

Reasoning

Suppressing cancellations is difficult to get right, and a developer should, at the very least, confirm they've understood the implications and different situations that a cancellation may occur.

A noqa comment can be used by the developer to confirm they've understood this. Alternatively, a couple of safe code patterns may be allowed without needing the noqa. Probably, if there is both a if task.done(): condition and a if asyncio.current_task().cancelling() check in the handler, then the warning is not needed (also, if there is an unconditional raise).

Documentation could link to https://superfastpython.com/asyncio-task-cancellation-best-practices/ for example (particularly, "Practice #1: Do Not Consume CancelledError", but there doesn't appear to be anchors to link to a section).

Possibly a separate rule could be to ensure that code which does suppress the exception also calls .uncancel():
https://superfastpython.com/asyncio-cancel-task-cancellation/