Title: asyncio.create_task() documentation should mention user needs to keep reference to the task
Type: enhancement Stage:
Components: Documentation Versions: Python 3.11, Python 3.10, Python 3.9
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: bernat, docs@python
Priority: normal Keywords:

Created on 2021-07-18 06:01 by bernat, last changed 2021-07-18 06:01 by bernat.

Messages (1)
msg397741 - (view) Author: Vincent Bernat (bernat) Date: 2021-07-18 06:01
asyncio will only keep weak references to alive tasks (in `_all_tasks`). If a user does not keep a reference to a task and the task is not currently executing or sleeping, the user may get "Task was destroyed but it is pending!".

I would suggest adding the following paragraph to `create_task()` documentation:

Python only keeps weak references to the scheduled tasks. To avoid the task being destroyed by the garbage collector while still pending, a reference to it should be kept until the task is done.

And maybe an example in case a user wants something "fire and forget"?

running_tasks = set()
# [...]
task = asyncio.create_task(some_background_function())
task.add_done_callback(lambda t: running_tasks.remove(t))

The same applies to ensure_future as it now uses create_task, so maybe a "See create_task()".
Date User Action Args
2021-08-24 02:30:11ncoghlanlinkissue42538 superseder
2021-07-18 06:01:26bernatcreate