Meaning
Wraps a coroutine so that if the outer awaiting task is cancelled, the inner coroutine continues running instead of being cancelled. This addresses the pain point of critical background operations (like database commits or cleanup) being prematurely aborted when a parent task receives a cancellation request. You reach for it whenever a coroutine must complete even if the caller is cancelled.
Primary Function
Concurrency
Communicative Purpose
Prevents critical async operations from being cancelled when the enclosing task is cancelled.
Pattern
await asyncio.shield(coro())
Core Structure
await asyncio.shield(...)
Função primária
Concurrency
Propósito comunicativo
Prevents critical async operations from being cancelled when the enclosing task is cancelled.
Situações de gatilho
Async servers: a client disconnects mid-request but the database write must still complete. Task orchestration: a timeout on asyncio.wait_for should not abort the underlying work. Graceful shutdown: cleanup coroutines must finish even if the host task is cancelled.
Contextos
Python asyncio applications, async web frameworks (FastAPI, aiohttp), task orchestration pipelines, server-side event loops.
Padrão
await asyncio.shield(coro())
Estrutura central
await asyncio.shield(...)
Slots de substituição
coro: awaitable coroutine object that must survive cancellation
Colocados típicos
- asyncio.create_task
- asyncio.gather
- asyncio.wait_for
- asyncio.CancelledError
- try/except
Substituições comuns
- Catching CancelledError manually and re-raising after the coroutine finishes — more verbose but gives finer control over partial cancellation. asyncio.Task with explicit cancellation guards — heavier but supports multiple waiters.
Erros comuns
Forgetting to re-raise CancelledError after shield completes, which silently swallows the cancellation and corrupts the event loop's cancellation propagation. Passing a bare coroutine function instead of calling it (shield expects an awaitable, not a function reference). Assuming shield makes the coroutine uncancelable from all sources — another explicit cancel() call on the inner task will still cancel it.
Similar / contraste
asyncio.create_task — schedules concurrently but does not protect from cancellation. asyncio.wait_for — imposes a timeout and cancels the coroutine on expiry (opposite intent). asyncio.Task.cancel — the cancellation mechanism that shield defends against.
Interferências
Coming from JavaScript: may expect Promise cancellation to propagate like JS AbortController — Python's shield only protects from the outer task's cancellation, not from direct task.cancel() on the inner task. Coming from Go: may expect context cancellation to always propagate to children — shield deliberately breaks that propagation for the shielded coroutine.
Família do chunk
- asyncio.shield
- asyncio.create_task
- asyncio.gather
- asyncio.wait_for
- asyncio.CancelledError
Nuance
Do NOT use shield when the coroutine's result is truly disposable or when cancellation should propagate for consistency. The shielded coroutine still consumes event loop resources after the outer task is cancelled, which can delay shutdown. If the shielded coroutine itself is awaited by multiple tasks, only the shield-wrapped caller is protected — other awaiters will still see cancellation.
Efeito pragmático
Ensures critical side-effect operations (database writes, network acknowledgments, resource cleanup) complete even when the requesting task is cancelled, preventing data loss and resource leaks in production async systems.
Dica de memória
Like a bomb shelter: the explosion (cancellation) happens outside, but the person inside (the coroutine) keeps living. The shelter doesn't stop explosions — it just keeps one person safe from them.
Nota
shield returns a Future that resolves to the coroutine's result; if the outer task is cancelled, the shielded coroutine keeps running but the awaiting call raises CancelledError. You must still await the original coroutine's result separately if you need it after cancellation.
Upgrade path
Custom cancellation-scoped task groups (e.g. anyio cancellation scopes) for fine-grained control over which subtasks survive cancellation.
Log in to save chunks.