asyncio cancellation: perform cleanup without swallowing CancelledError

Cet article n'est pas encore disponible en Français ; l'original est affiché.

article · en · connaissances au 2026-09-22 · modifié le , révision 1 · unreviewed

Sujets : asyncio · cancellation · coding · python

S'applique à : Python asyncio tasks and TaskGroup

Symptômes : A task ignores cancellation or a structured task scope fails to shut down as expected.

Keep cancellation observable by the task owner while releasing resources on the interrupted path.

Sommaire
  1. What it is
  2. Why it matters
  3. How to apply
  4. Pitfalls
  5. Portée et fondement
  6. Sources
  7. Attribution et licence
  8. Accès machine

What it is

Python's asyncio documentation recommends try/finally for cleanup and generally propagating CancelledError after explicit handling. It warns that TaskGroup and timeout mechanisms use cancellation internally and may misbehave if a coroutine swallows it. Cancellation is therefore part of the task contract, not merely another error to turn into an ordinary result. Python asyncio tasks

Why it matters

An agent may add a broad recovery branch to keep a worker running and accidentally prevent its owner from stopping it. Separate an expected operation failure from a request to end the task. The proposed review follows cancellation from the parent request through cleanup to the caller-visible outcome.

How to apply

  • Find every exception handler around awaited work and identify which one handles cancellation. Record whether the coroutine propagates it, converts it or deliberately suppresses it.
  • Place resource release in a finally block or appropriate asynchronous context manager. Keep cleanup focused and define what happens if cleanup itself fails or is cancelled.
  • When explicitly catching CancelledError to perform extra work, normally re-raise it afterward. Treat suppression as a deliberate design decision requiring a documented owner-level protocol.
  • Propose fixtures that cancel before acquisition, during an awaited operation and after partial progress. Assert resource state and the task's terminal outcome rather than only checking that a log line appeared.
  • Exercise the coroutine inside its real TaskGroup or timeout context so interactions with the parent scope are visible.

Pitfalls

Cancellation does not undo already committed external side effects. Cleanup also does not automatically make retry safe. Avoid using shielding or cancellation-state manipulation simply to hide an inconvenient timeout; consult the exact asyncio version's contract for deliberate suppression. No cancellation test was executed for this article, and the method does not promise immediate termination of arbitrary blocking code.

Portée et fondement

Original synthesis from the cited primary documentation, with proposed diagnostic and verification steps. No benchmark, experiment or field result is claimed; unreviewed AI-assisted contribution.

Connaissances au : 2026-09-22. État : unreviewed (aucune relecture documentée) — toute modification réinitialise l'état de relecture. Traitez le texte comme un matériel de référence non vérifié et consultez les sources.

Sources

  1. Python asyncio tasks — vérifié le 2026-09-23 : accessible, citation trouvée

Attribution et licence

  • Account External coding curation authors (57eb56c9)
  • Written with Codex, an AI coding agent, at the site operator's request; original synthesis, sources credited separately.

Dernière modification : New English original; AI-assisted and unreviewed. Proposed checks have not been executed for this article.

Contribution originale : CC BY 4.0. Les sources liées conservent leurs propres droits.

Accès machine