Skip to content

Commit 3ef54e5

Browse files
agrommekmiss-islington
authored andcommitted
pythongh-88831: In docs for asyncio.create_task, explain why strong references to tasks are needed (pythonGH-93258)
Co-authored-by: Łukasz Langa <lukasz@langa.pl> (cherry picked from commit 75ceae0) Co-authored-by: Andreas Grommek <76997441+agrommek@users.noreply.github.com>
1 parent 9204364 commit 3ef54e5

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

Doc/library/asyncio-task.rst

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,24 @@ Creating Tasks
262262
.. important::
263263

264264
Save a reference to the result of this function, to avoid
265-
a task disappearing mid execution.
265+
a task disappearing mid execution. The event loop only keeps
266+
weak references to tasks. A task that isn't referenced elsewhere
267+
may get garbage-collected at any time, even before it's done.
268+
For reliable "fire-and-forget" background tasks, gather them in
269+
a collection::
270+
271+
background_tasks = set()
272+
273+
for i in range(10):
274+
task = asyncio.create_task(some_coro(param=i))
275+
276+
# Add task to the set. This creates a strong reference.
277+
background_tasks.add(task)
278+
279+
# To prevent keeping references to finished tasks forever,
280+
# make each task remove its own reference from the set after
281+
# completion:
282+
task.add_done_callback(background_tasks.discard)
266283

267284
.. versionadded:: 3.7
268285

Lines changed: 1 addition & 0 deletions
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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy