PyDocs

Nav

Networking and Interprocess Communication

shield

asyncio

async function (source) Deprecated 3.10not WASI
  • shield(aw)
Deprecated since 3.10. Deprecation warning is emitted if aw is not Future-like object and there is no running event loop.
Wait for a future, shielding it from cancellation.

The statement

    task = asyncio.create_task(something())
    res = await shield(task)

is exactly equivalent to the statement

    res = await something()

*except* that if the coroutine containing it is cancelled, the
task running in something() is not cancelled.  From the POV of
something(), the cancellation did not happen.  But its caller is
still cancelled, so the yield-from expression still raises
CancelledError.  Note: If something() is cancelled by other means
this will still cancel shield().

If you want to completely ignore cancellation (not recommended)
you can combine shield() with a try/except clause, as follows:

    task = asyncio.create_task(something())
    try:
        res = await shield(task)
    except CancelledError:
        res = None

Save a reference to tasks passed to this function, to avoid
a task disappearing mid-execution. The event loop only keeps
weak references to tasks. A task that isn't referenced elsewhere
may get garbage collected at any time, even before it's done.
Changed in 3.10
  • 3.10: Removed the loop parameter.
0 Examples
No examples for asyncio/shield.
See Also
No see-alsos for asyncio/shield
0 Notes
No notes for shield