Skip to content

Commit 75ceae0

Browse files
agrommekambv
andauthored
gh-88831: In docs for asyncio.create_task, explain why strong references to tasks are needed (GH-93258)
Co-authored-by: Łukasz Langa <[email protected]>
1 parent f0d0be3 commit 75ceae0

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Doc/library/asyncio-task.rst

+18-1
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,24 @@ Creating Tasks
226226
.. important::
227227

228228
Save a reference to the result of this function, to avoid
229-
a task disappearing mid execution.
229+
a task disappearing mid execution. The event loop only keeps
230+
weak references to tasks. A task that isn't referenced elsewhere
231+
may get garbage-collected at any time, even before it's done.
232+
For reliable "fire-and-forget" background tasks, gather them in
233+
a collection::
234+
235+
background_tasks = set()
236+
237+
for i in range(10):
238+
task = asyncio.create_task(some_coro(param=i))
239+
240+
# Add task to the set. This creates a strong reference.
241+
background_tasks.add(task)
242+
243+
# To prevent keeping references to finished tasks forever,
244+
# make each task remove its own reference from the set after
245+
# completion:
246+
task.add_done_callback(background_tasks.discard)
230247

231248
.. versionadded:: 3.7
232249

Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Augmented documentation of asyncio.create_task(). Clarified the need to keep strong references to tasks and added a code snippet detailing how to to this.

0 commit comments

Comments
 (0)