Asyncio Shield Critical Section

Protect critical sections from cancellation with asyncio.shield for atomic operations.

PythonResilience

Code

snippet
import asyncio

async def critical_operation():
    await asyncio.sleep(2)
    return 'done'

async def handler():
    try:
        result = await asyncio.shield(critical_operation())
        return result
    except asyncio.CancelledError:
        print('handler cancelled, critical still running')
        raise

async def main():
    task = asyncio.create_task(handler())
    await asyncio.sleep(0.5)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        pass