Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-88831: In docs for asyncio.create_task, explain why strong references to tasks are needed #93258

Merged
merged 4 commits into from
Jun 7, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion Doc/library/asyncio-task.rst
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,25 @@ Creating Tasks
.. important::

Save a reference to the result of this function, to avoid
a task disappearing mid execution.
a task disappearing mid execution. The event loop only keeps
weak references to all task. Without a strong reference, the
task may get garbage-collected at any time. If you want to have
"fire-and-forget" background tasks you can do something like this::

# create an empty set to store references to background tasks
background_tasks = set()

# start 10 background tasks
for i in range(10):
task = asyncio.create_task(some_coro(param=i))

# Add task to set. This creates a strong reference.
background_tasks.add(task)

# To prevent accumulation of references to already finished
# tasks, make each task remove its own reference from set after
# completion:
task.add_done_callback(lambda t: background_tasks.discard(t))
ambv marked this conversation as resolved.
Show resolved Hide resolved

.. versionadded:: 3.7

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +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.