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.
.. 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::
The statement::
- res = await shield(something())
+ task = asyncio.create_task(something())
+ res = await shield(task)
is equivalent to::
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.
The statement
- res = await shield(something())
+ task = asyncio.create_task(something())
+ res = await shield(task)
is exactly equivalent to the statement
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():