Content · Programming · Python

Python asyncio Cancellation and CancelledError

Cancellation asks a Task to stop and usually raises asyncio.CancelledError at its next suspension point.

5 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Cancellation asks a Task to stop and usually raises asyncio.

Understanding the Concept


Cancellation asks a Task to stop and usually raises asyncio.CancelledError at its next suspension point. Use try/finally to release resources, then normally allow cancellation to propagate.

CancelledError subclasses BaseException; a broad except Exception does not normally catch it.

How the event loop makes progress


When a coroutine reaches await, it may suspend so another ready Task can execute. This scheduling is cooperative: blocking operations that do not yield hold up every coroutine sharing the event loop. Assign ownership of background tasks, put timeouts around operations that may wait, and release resources on cancellation.

An async function does not automatically use several CPU cores. Use async-compatible I/O for waiting tasks and executors or separate processes for blocking or CPU-heavy work when appropriate.

Worked Example


Read the code from the first line to the last. Identify which values are inputs, which operation is being demonstrated and what should happen before running it.

import asyncio

async def task_body():
    try:
        await asyncio.sleep(5)
    finally:
        print("Cleanup executed")

async def main():
    task = asyncio.create_task(task_body())
    await asyncio.sleep(0)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("Cancelled")

asyncio.run(main())

Walkthrough: What Each Part Does


  • The imports make asyncio available. These are standard-library building blocks unless the example explicitly names an external tool.
  • The definition task_body, main creates reusable behavior. Its body runs when called, awaited or instantiated; defining it alone does not run the body of an ordinary function.
  • Each await is a suspension point. When the awaited operation is not ready, the loop can schedule other tasks instead of blocking the entire thread.
  • The try/except or finally block states what happens when an operation fails; cleanup and error reporting are part of the example, not optional extras.
  • The coordination call waits for a result or a completion condition. Predict what would happen if the worker failed or never became ready.

This demonstration focuses on one practical behavior. Before changing several lines, vary one input or one configuration choice and check whether the result changes for the reason you expected.

Example Output


Cleanup executed
Cancelled

The output above was captured by running the example in the available Python environment. The order of concurrent events, durations and platform-dependent values can legitimately differ on your computer.

Important Behavior and Edge Cases


Swallowing CancelledError without a clear plan, disrupting structured concurrency and timeout mechanisms.

CancelledError subclasses BaseException; a broad except Exception does not normally catch it.

Practice Exercise


Add a context-managed resource to task_body and verify its cleanup after cancellation.

Write down the result you expect before running your changed code. Check at least one normal case and one boundary or failure case. If your example starts workers or opens resources, verify how they are cleaned up.

Further reading: official documentation and API reference.

Common Beginner Mistakes


  • Swallowing CancelledError without a clear plan, disrupting structured concurrency and timeout mechanisms.
  • Calling a blocking function inside the event loop, or creating tasks without awaiting, cancelling or owning them.

Key Takeaways


  • Cancellation asks a Task to stop and usually raises asyncio.
  • CancelledError subclasses BaseException; a broad except Exception does not normally catch it.
  • Practice: Add a context-managed resource to task_body and verify its cleanup after cancellation.
Share this resourceSend this page to someone who may find it useful.