PythiloLesson 5 of 12 · progress kept in this browser

Cancel and await the task you own

Cancellation is a request delivered at an await point. Calling cancel without awaiting the task leaves cleanup and exceptions unresolved. A parent that owns a task should request cancellation, await completion and suppress only the expected CancelledError.

The coroutine may already have finished successfully or failed before cancellation. Those outcomes must retain their meaning. Catching every exception would hide a broken worker. The tests synchronize through an Event so they verify the actual cleanup path without sleeps that depend on device speed.

import asyncio
async def main():
    task=asyncio.create_task(asyncio.sleep(1))
    task.cancel()
    try: await task
    except asyncio.CancelledError:
        print("cancelled")
asyncio.run(main())
Your task

Implement async stop_owned(task). Cancel and await it; return None for cancellation or its successful result. Propagate other failures.