Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

asyncio.shield

Protects an underlying task from cancellation requested through the shielding awaitable.

Version: Python 3.14; repository image, production runtime not attested

Syntax

await asyncio.shield(aw)

Protects an underlying task from cancellation requested through the shielding awaitable.

Cancelling the outer shield can still cancel the caller’s wait. Retain the task handle to retrieve the underlying result separately.

Await through a shield to isolate a task from cancellation through that wrapper. The caller still receives CancelledError; the underlying task keeps running unless separately cancelled. Direct cancellation of that task reaches the shield. Hold a strong reference to the task. In the sample outer is cancelled, but the gate releases the original task with True.

import asyncio
async def main():
    e = asyncio.Event()
    t = asyncio.create_task(e.wait())
    s = asyncio.shield(t)
    s.cancel()
    try:
        await s
    except asyncio.CancelledError:
        assert not t.cancelled()
    e.set()
    assert await t is True
asyncio.run(main())

Examples

import asyncio

async def main():
    gate = asyncio.Event()
    task = asyncio.create_task(gate.wait())
    outer = asyncio.shield(task)
    outer.cancel()
    gate.set()
    print(outer.cancelled(), await task, task.cancelled())

asyncio.run(main())

Result

True True False

Await through a shield to isolate a task from cancellation through that wrapper. The caller still receives CancelledError; the underlying task keeps running unless separately cancelled. Direct cancellation of that task reaches the shield. Hold a strong reference to the task. In the sample outer is cancelled, but the gate releases the original task with True.

Sources