From 6698c1f8ec8a39a11cfd8a5b5aeb9065a32d3379 Mon Sep 17 00:00:00 2001 From: Thomas Rachel <157142388+glglgl-de@users.noreply.github.com> Date: Wed, 17 Jun 2026 00:21:45 +0200 Subject: [PATCH] Keep a reference to the created task The Python documentation states that asyncio only keeps a weak reference to a created task. If the caller doesn't keep it, it might be garbage collected. Thus, keep a reference in a set. Remove that as soon as the task is done. Besides, let the wrapper function return that task for the case that someone wants to access the return value of the wrapped function. --- async_tkinter_loop/async_tkinter_loop.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/async_tkinter_loop/async_tkinter_loop.py b/async_tkinter_loop/async_tkinter_loop.py index 7e23abb..9547629 100644 --- a/async_tkinter_loop/async_tkinter_loop.py +++ b/async_tkinter_loop/async_tkinter_loop.py @@ -53,6 +53,8 @@ def async_mainloop(root: tk.Tk, event_loop: asyncio.AbstractEventLoop | None = N P = ParamSpec("P") +_tasks = set() + def async_handler( async_function: Callable[P, Coroutine[Any, Any, None]], @@ -109,6 +111,8 @@ async def some_async_function(): @wraps(async_function) def wrapper(*handler_args) -> None: loop = event_loop or get_event_loop() - loop.create_task(async_function(*handler_args, *args, **kwargs)) + task = loop.create_task(async_function(*handler_args, *args, **kwargs)) + _tasks.add(task) + task.add_done_callback(_tasks.discard) return wrapper