async-timeout
async-timeout copied to clipboard
Add `msg` to `task.cancel()` method to allow distinguish the source of cancellation
How about adding msg argument to task.cancel()?
TL;DR:
def _on_timeout(self, task: "asyncio.Task[None]") -> None:
task.cancel(msg="timeout") # <--- add the reason of cancellation
self._state = _State.TIMEOUT
# drop the reference early
self._timeout_handler = None
This would be useful to distinguish the reason of cancellation in library's user programs.
import asyncio
class CustomTask(asyncio.Task): def cancel(self, msg=None): self._msg = msg super().cancel()
def _on_timeout(self, task: "asyncio.Task[None]") -> None: task.cancel(msg="timeout") # Adding a custom reason for cancellation self._state = _State.TIMEOUT # Drop the reference early self._timeout_handler = None
Replace asyncio.Task with CustomTask wherever you want to use it
async def main(): loop = asyncio.get_event_loop() task = loop.create_task(async_func()) await asyncio.sleep(1) task.cancel("custom_reason")
loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close()