Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Sensibilisation à
l'Intelligence Artificielle
Voir le programme détaillé
Module « asyncio » Python 3.13.2

Fonction shield - module asyncio

Signature de la fonction shield

def shield(arg) 

Description

help(asyncio.shield)

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.


Vous êtes un professionnel et vous avez besoin d'une formation ? Coder avec une
Intelligence Artificielle
Voir le programme détaillé