"""Keep resource leases until a blocking operation actually finishes on cancellation.""" import asyncio async def complete_thread(function, *args): task = asyncio.create_task(asyncio.to_thread(function, *args)) try: return await asyncio.shield(task) except asyncio.CancelledError: # asyncio cancellation cannot stop a Python thread. Do not close its file # or release its decoder/upload permit while it is still using them. try: await asyncio.shield(task) except Exception: pass raise