liveBook · Manning

CancelledError

As explained in Python Concurrency with asyncio

CancelledError is the asyncio exception raised in a task when cancellation is delivered while the task is being awaited or resumed.

CancelledError is raised when a cancelled asyncio task is awaited. Cancellation is cooperative: calling cancel() does not interrupt ordinary Python code immediately. The exception appears at the current or next await point, if one exists. section 2.4.1

Stopping an overlong task

Create a ten-second task, check it once per second, and call cancel() after five seconds. Awaiting the task inside try/except CancelledError lets the application report that it stopped the operation. section 2.4.1

Listing 2.11 Canceling a task
import asyncio
from asyncio import CancelledError
from util import delay
 
 
async def main():
    long_task = asyncio.create_task(delay(10))
 
    seconds_elapsed = 0
 
    while not long_task.done():
        print('Task not finished, checking again in a second.')
        await asyncio.sleep(1)
        seconds_elapsed = seconds_elapsed + 1
        if seconds_elapsed == 5:
            long_task.cancel()
 
    try:
        await long_task
    except CancelledError:
        print('Our task was cancelled')
 
asyncio.run(main())

Runnable listing showing task creation, periodic status checks, cancellation, and CancelledError handling. section 2.4.1

How Python Concurrency with asyncio covers it

How deep it goes
Explains cancellation timing and await-point behavior, while deferring broader shutdown coordination.
Examples
Uses a five-second task limit and cancelled echo-server tasks during application shutdown.
What it assumes
Assumes basic asyncio tasks and await expressions, while teaching cancellation behavior through concrete code.
What you can do after
Apply it via asyncio to stop overdue tasks and handle cancellation without leaving cleanup unfinished.
How it connects
Links asyncio tasks, await expressions, event loops, timeouts, and finally blocks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.