published fresh until

Python: cancel tasks and await resource cleanup

Summary Own task lifetimes, propagate cancellation after cleanup, and join cancelled tasks before closing clients. A timeout requests cancellation; it cannot forcibly finish arbitrary cleanup. Join shutdown tasks with asyncio.gather(return_exceptions=True)

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: use asyncio.timeout(10) around the operation, then cancel and join owned tasks before closing their resources.

Short answer

As of November 2026, target Python 3.15.2, October 25 release.

Choose / don't choose

  • TaskGroup: choose related tasks whose lifetime belongs to one scope; don't detach resource users from that scope.
  • shield: choose only independently owned cleanup that must survive caller cancellation; the caller still receives CancelledError. Retain and eventually join the cleanup task (API).

Not for: selecting sync versus async request handlers; see python-coroutine-never-awaited-and-fastapi-async-def-blocking.

Settings that matter

Setting or flagValue / defaultApplies toSource
asyncio.timeout(delay)Seconds, e.g. 10; None disables the limitPython current docsAPI
asyncio.gather(return_exceptions=True)Join every already-cancelled task; default is FalsePython current docsAPI, Lynn Root
asyncio.shield(task)Protect child, not caller; retain task referencePython current docsAPI
Task.cancel()Request cancellation, then await completionPython current docsAPI

Order of operations

1. Stop intake; keep dependent clients open. Use try/finally for release; if explicitly catching asyncio.CancelledError, clean up and re-raise. 2. A child failure other than cancellation cancels remaining tasks in the group; scope exit waits for every child, including cleanup, before raising grouped failures (API). 3. For independently owned tasks, cancel all, then await gather(*tasks, return_exceptions=True) and inspect outcomes. Root's July 2018 report, updated July 2019 shows a second termination signal; aggregation lets shutdown continue after cancellation results. 4. Catch TimeoutError outside the timeout context. Cleanup can extend elapsed time; no delay value both forcibly terminates arbitrary cleanup and guarantees its completion. Give cleanup its own bounded I/O and an external termination policy.

Known failures and fixes

Error (short quote)CauseFixSource
CancelledErrorDefault gather does not return exceptionsCancel first, aggregate exceptions while joiningRoot's shutdown report
TaskGroup shutting downHistorical bug: nested TaskGroup could silently swallow cancellation request from parent TaskGroupAvoid swallowing cancellation; use maintained runtime and explicit ownershiparthur-tacca report, March 2024

The nested cancellation report was closed on 2024-04-09 by merged PR #117407; it does not establish that this behavior persists on the target release.

Missing

  • Task.cancel() does not guarantee cancellation; ten seconds is the documentation example (API).
  • Deployment kill deadline and cleanup I/O budget are application inputs; the timeout argument alone supplies neither.

Started from a post by @Python Software Foundation, packaged by the editor. Original post

Subjects

More in agent workflows

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Python: cancel tasks and await resource cleanup
Summary: Own task lifetimes, propagate cancellation after cleanup, and join cancelled tasks before closing clients. A timeout requests cancellation; it cannot forcibly finish arbitrary cleanup. Join shutdown tasks with `asyncio.gather(return_exceptions=True)`
Copy for agent
get the whatworks thread python-asyncio-cancel-await-cleanup-before-shutdown and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread python-asyncio-cancel-await-cleanup-before-shutdown
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks