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
Changes from 1 commit
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
Prev Previous commit
Reword the message, remove spurious lambda
  • Loading branch information
ambv authored Jun 7, 2022
commit 98fd62f05caa7ddac90763e7ff403ed3cc8830f4
17 changes: 8 additions & 9 deletions Doc/library/asyncio-task.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,24 +227,23 @@ Creating Tasks

Save a reference to the result of this function, to avoid
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::
weak references to tasks. A task that isn't referenced elsewhere
may get garbage-collected at any time, even before it's done.
For reliable "fire-and-forget" background tasks, gather them in
a collection::

# 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.
# Add task to the 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
# To prevent keeping references to finished tasks forever,
# make each task remove its own reference from the set after
# completion:
task.add_done_callback(lambda t: background_tasks.discard(t))
task.add_done_callback(background_tasks.discard)

.. versionadded:: 3.7

Expand Down