async-timeout icon indicating copy to clipboard operation
async-timeout copied to clipboard

Add `msg` to `task.cancel()` method to allow distinguish the source of cancellation

Open achimnol opened this issue 3 years ago • 1 comments
trafficstars

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.

achimnol avatar Jul 05 '22 07:07 achimnol

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()

ljluestc avatar Sep 05 '23 00:09 ljluestc