mirror of
https://github.com/python/cpython.git
synced 2025-08-27 04:05:34 +00:00
gh-94972: document that shield users need to keep a reference to their task (GH-96724)
Co-authored-by: Thomas Grainger <tagrain@gmail.com>
Co-authored-by: Guido van Rossum <gvanrossum@gmail.com>
(cherry picked from commit 6281affee6
)
Co-authored-by: Hendrik Makait <hendrik.makait@gmail.com>
This commit is contained in:
parent
7033dc8adc
commit
335bd1ee8b
3 changed files with 23 additions and 7 deletions
|
@ -848,7 +848,8 @@ def shield(arg):
|
|||
|
||||
The statement
|
||||
|
||||
res = await shield(something())
|
||||
task = asyncio.create_task(something())
|
||||
res = await shield(task)
|
||||
|
||||
is exactly equivalent to the statement
|
||||
|
||||
|
@ -864,10 +865,16 @@ def shield(arg):
|
|||
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(something())
|
||||
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.
|
||||
"""
|
||||
inner = _ensure_future(arg)
|
||||
if inner.done():
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue