]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-104091: Suggest TaskGroup for running background tasks in asyncio.create_task...
authorKumar Aditya <kumaraditya@python.org>
Tue, 4 Aug 2026 06:30:27 +0000 (12:00 +0530)
committerGitHub <noreply@github.com>
Tue, 4 Aug 2026 06:30:27 +0000 (12:00 +0530)
Doc/library/asyncio-task.rst

index b6f3662862eb38fb8f81b7c31ce8c543b637b978..38364138a17d7903debd635c1a63998d60fe7113 100644 (file)
@@ -288,6 +288,17 @@ Creating tasks
               # completion:
               task.add_done_callback(background_tasks.discard)
 
+      Note that this approach never awaits the tasks, so if a task
+      fails, its exception is never retrieved and asyncio logs a
+      "Task exception was never retrieved" message when the task is
+      garbage collected.  To avoid this, use :class:`asyncio.TaskGroup`
+      which keeps a strong reference to each task, awaits them and
+      propagates their exceptions::
+
+          async with asyncio.TaskGroup() as tg:
+              for i in range(10):
+                  tg.create_task(some_coro(param=i))
+
    .. versionadded:: 3.7
 
    .. versionchanged:: 3.8