Back
+30 XP
Concept

Cancellation Token Pattern in asyncio

Calling task.cancel() directly throws asyncio.CancelledError abruptly at the next await, potentially corrupting uncommitted database state. A CancellationToken provides cooperative cancellation, allowing long-running operations to safely inspect flags, cleanup resources, and exit cleanly.

python
class CancellationToken:
    def __init__(self):
        self.is_cancelled = False
    def cancel(self):
        self.is_cancelled = True

# Cancellation Token Pattern in asyncio Abruptly calling `task.cancel()` on an active coroutine injects an `asyncio.CancelledError` at whichever line happens to be yielding. If that yield occurs right between debiting an account and crediting another, your database is corrupted. 💀🛑 The **Cancellation Token** pattern implements *cooperative cancellation*. Workers periodically inspect `token.is_cancelled` or call `token.throw_if_cancelled()` at defined, safe transaction boundaries, ensuring partial writes are never abandoned halfway. ```python class CancellationToken: def __init__(self): self._cancelled = False @property def is_cancelled(self) -> bool: return self._cancelled def cancel(self): self._cancelled = True ``` ## Pop Quiz Why is cooperative token-based cancellation safer than abruptly terminating coroutines with `task.cancel()`? - [ ] It lets coroutines finish atomic transactions and release file locks before exiting gracefully. - [ ] It disables the Python garbage collector to protect in-flight heap variables. - [ ] It redirects pending socket payloads directly into the operating system pipe buffer. - [ ] It bypasses asynchronous context manager __aexit__ calls entirely. ## Real-World Challenge Implement a robust `CancellationToken` featuring `cancel()`, `is_cancelled`, `register(callback)`, and `throw_if_cancelled()`. If a callback is registered *after* the token was already cancelled, invoke it immediately. <details> <summary>Solution</summary> ```python import asyncio class CancellationToken: def __init__(self): self._cancelled = False self._callbacks = [] @property def is_cancelled(self) -> bool: return self._cancelled def cancel(self): if not self._cancelled: self._cancelled = True for cb in self._callbacks: cb() def register(self, callback): if self._cancelled: callback() else: self._callbacks.append(callback) def throw_if_cancelled(self): if self._cancelled: raise asyncio.CancelledError("Operation cancelled via cooperative token") # Verification async def run_test(): token = CancellationToken() cleanup_ran = False def on_cancel(): nonlocal cleanup_ran cleanup_ran = True token.register(on_cancel) async def long_worker(tok: CancellationToken): cycles = 0 while not tok.is_cancelled: cycles += 1 await asyncio.sleep(0.01) return cycles task = asyncio.create_task(long_worker(token)) await asyncio.sleep(0.03) token.cancel() completed_cycles = await task assert token.is_cancelled is True assert cleanup_ran is True assert completed_cycles >= 2 asyncio.run(run_test()) ``` </details>