Question
Cleanup not executed on CancelledError before yield in FastAPI dependency
Ari River
0 reputation · 08 Oct 2022, 15:54 UTC
22.7K views0
Determine whether the cleanup code in a FastAPI yield‑dependency runs when an asyncio.CancelledError is raised during the dependency’s setup phase, i.e., before the yield statement.
The behavior depends on how the dependency is invoked and on the Python/asyncio version, with reports that try/finally blocks around the yield may be skipped if cancellation occurs before the yield point. This uncertainty affects resource release and transaction rollback reliability.
- Does the try/finally block surrounding the yield execute when CancelledError occurs before yield?
- Does the outcome differ between Python 3.10 and Python 3.11+ with asyncio.TaskGroup?
- What minimal reproduction shows the cleanup being omitted or executed?