mirror of
https://github.com/python/cpython.git
synced 2025-08-04 00:48:58 +00:00
gh-94972: document that shield users need to keep a reference to their task (#96724)
Co-authored-by: Thomas Grainger <tagrain@gmail.com> Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
This commit is contained in:
parent
50a70a083d
commit
6281affee6
3 changed files with 23 additions and 7 deletions
|
@ -55,7 +55,7 @@ Future Functions
|
|||
preferred way for creating new Tasks.
|
||||
|
||||
Save a reference to the result of this function, to avoid
|
||||
a task disappearing mid execution.
|
||||
a task disappearing mid-execution.
|
||||
|
||||
.. versionchanged:: 3.5.1
|
||||
The function accepts any :term:`awaitable` object.
|
||||
|
|
|
@ -254,9 +254,9 @@ Creating Tasks
|
|||
.. important::
|
||||
|
||||
Save a reference to the result of this function, to avoid
|
||||
a task disappearing mid execution. The event loop only keeps
|
||||
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.
|
||||
may get garbage collected at any time, even before it's done.
|
||||
For reliable "fire-and-forget" background tasks, gather them in
|
||||
a collection::
|
||||
|
||||
|
@ -520,7 +520,8 @@ Shielding From Cancellation
|
|||
|
||||
The statement::
|
||||
|
||||
res = await shield(something())
|
||||
task = asyncio.create_task(something())
|
||||
res = await shield(task)
|
||||
|
||||
is equivalent to::
|
||||
|
||||
|
@ -539,11 +540,19 @@ Shielding From Cancellation
|
|||
the ``shield()`` function should be combined with a try/except
|
||||
clause, as follows::
|
||||
|
||||
task = asyncio.create_task(something())
|
||||
try:
|
||||
res = await shield(something())
|
||||
res = await shield(task)
|
||||
except CancelledError:
|
||||
res = None
|
||||
|
||||
.. important::
|
||||
|
||||
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.
|
||||
|
||||
.. versionchanged:: 3.10
|
||||
Removed the *loop* parameter.
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue