Skip to content

Commit c0f34a6

Browse files
committed
gh-94972: document that shield users need to keep a reference to their task
1 parent 7b617be commit c0f34a6

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

Doc/library/asyncio-task.rst

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,10 @@ Shielding From Cancellation
520520

521521
The statement::
522522

523-
res = await shield(something())
523+
task = asyncio.create_task(something())
524+
background_tasks.add(task)
525+
task.add_done_callback(background_tasks.discard)
526+
res = await shield(task)
524527

525528
is equivalent to::
526529

@@ -539,11 +542,23 @@ Shielding From Cancellation
539542
the ``shield()`` function should be combined with a try/except
540543
clause, as follows::
541544

545+
task = asyncio.create_task(something())
546+
background_tasks.add(task)
547+
task.add_done_callback(background_tasks.discard)
542548
try:
543-
res = await shield(something())
549+
res = await shield(task)
544550
except CancelledError:
545551
res = None
546552

553+
.. important::
554+
555+
Save a reference to tasks passed to this function, to avoid
556+
a task disappearing mid execution. The event loop only keeps
557+
weak references to tasks. A task that isn't referenced elsewhere
558+
may get garbage-collected at any time, even before it's done.
559+
For reliable "fire-and-forget" background tasks, gather them in
560+
a collection.
561+
547562
.. versionchanged:: 3.10
548563
Removed the *loop* parameter.
549564

0 commit comments

Comments
 (0)