diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2022-09-10 14:57:44 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-10 14:57:44 (GMT) |
commit | 9b710581a3c59bf8c92e27cd9da5d3b9750587fe (patch) | |
tree | 5cbb2925cebcb70d1fee31e9fe14b91e9c2368ea /Lib/asyncio | |
parent | 5a17200022eef19ea8a5594ebc440974b890238e (diff) | |
download | cpython-9b710581a3c59bf8c92e27cd9da5d3b9750587fe.zip cpython-9b710581a3c59bf8c92e27cd9da5d3b9750587fe.tar.gz cpython-9b710581a3c59bf8c92e27cd9da5d3b9750587fe.tar.bz2 |
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 6281affee6423296893b509cd78dc563ca58b196)
Co-authored-by: Hendrik Makait <hendrik.makait@gmail.com>
Diffstat (limited to 'Lib/asyncio')
-rw-r--r-- | Lib/asyncio/tasks.py | 11 |
1 files changed, 9 insertions, 2 deletions
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index c4bedb5..f391586 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -809,7 +809,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 @@ -825,10 +826,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(): |