Advertisement
Advanced Python, Concurrency (asyncio/threading/multiprocessing)

How do you correctly cancel a running asyncio task, and how should the task itself handle the resulting CancelledError?

Short answer

Call task.cancel() to request cancellation, which raises asyncio.CancelledError inside the task at its next 'await' suspension point — the task SHOULD let this exception propagate (after any necessary cleanup in a finally block) rather than silently catching and suppressing it…

Save Python mock interview
Advertisement
AModel answer
Call task.cancel() to request cancellation, which raises asyncio.CancelledError inside the task at its next 'await' suspension point — the task SHOULD let this exception propagate (after any necessary cleanup in a finally block) rather than silently catching and suppressing it, since swallowing CancelledError breaks the task's ability to actually be cancelled.
async def long_running():
    try:
        await asyncio.sleep(100)
    except asyncio.CancelledError:
        print("Cleaning up before cancellation")
        raise  # MUST re-raise to properly complete cancellation

async def main():
    task = asyncio.create_task(long_running())
    await asyncio.sleep(1)
    task.cancel()
    await asyncio.gather(task, return_exceptions=True)
Real-world example
Cancelling a long-running background task (like a polling loop) cleanly when a user navigates away or a shutdown signal is received.
Likely follow-ups
  • What happens if a cancelled task's except block swallows CancelledError instead of re-raising it?
Related topics