KITFORMA · EDITORIAL ANSWER
How should an asyncio task clean up when it is cancelled?
KitForma editorial guide. Cancellation is delivered cooperatively at an await point. Swallowing it can break timeouts and structured-concurrency shutdown.
Step-by-step answer
finally; if you catch asyncio.CancelledError to record a cancellation, re-raise it after cleanup unless the design explicitly requires suppression. Test cancellation while the task is waiting, while it owns a resource and immediately after successful completion. Cleanup that itself awaits may need a carefully bounded design. A cancellation request is not proof that remote work was rolled back. For network writes, retain an operation identifier and reconcile the remote result instead of blindly retrying.Sources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.