From 17a432c1a3fdf3faa8ed1287389d4e233e7e511d Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Sun, 7 Jan 2018 10:41:51 +0200 Subject: [PATCH] uasyncio.core: Add cancel(coro) function. This also adds CancelledError exception and makes TimeoutError be a subclass of it. As well as adds default exception handler for it in the eventloop (which just skips re-adding this coro to the scheduling queue, as expected). --- uasyncio.core/uasyncio/core.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/uasyncio.core/uasyncio/core.py b/uasyncio.core/uasyncio/core.py index 84fdac5d..274883a7 100644 --- a/uasyncio.core/uasyncio/core.py +++ b/uasyncio.core/uasyncio/core.py @@ -15,7 +15,11 @@ def set_debug(val): log = logging.getLogger("uasyncio.core") -class TimeoutError(Exception): +class CancelledError(Exception): + pass + + +class TimeoutError(CancelledError): pass @@ -136,6 +140,10 @@ class EventLoop: if __debug__ and DEBUG: log.debug("Coroutine finished: %s", cb) continue + except CancelledError as e: + if __debug__ and DEBUG: + log.debug("Coroutine cancelled: %s", cb) + continue # Currently all syscalls don't return anything, so we don't # need to feed anything to the next invocation of coroutine. # If that changes, need to pass that value below. @@ -226,6 +234,12 @@ _stop_iter = StopIteration() sleep_ms = SleepMs() +def cancel(coro): + prev = coro.pend_throw(CancelledError()) + if prev is False: + _event_loop.call_soon(coro) + + class TimeoutObj: def __init__(self, coro): self.coro = coro