From 58d2cde098f864a3e9ff6c37ddf1c8d0a4b0da6e Mon Sep 17 00:00:00 2001 From: Bruno Alvalat Date: Wed, 31 Jul 2024 12:20:20 -0600 Subject: [PATCH] fix: avoid premature garbage collection of tasks (#2510) * avoid premature garbage collection of Client tasks * style(pre-commit): auto fixes from pre-commit.com hooks * remove typehint (pre-commit makes it non compatible with older python) * style(pre-commit): auto fixes from pre-commit.com hooks --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- discord/client.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/discord/client.py b/discord/client.py index 4cfaef59cf..1fc004f35b 100644 --- a/discord/client.py +++ b/discord/client.py @@ -256,6 +256,9 @@ def __init__( VoiceClient.warn_nacl = False _log.warning("PyNaCl is not installed, voice will NOT be supported") + # Used to hard-reference tasks so they don't get garbage collected (discarded with done_callbacks) + self._tasks = set() + async def __aenter__(self) -> Client: loop = asyncio.get_running_loop() self.loop = loop @@ -423,8 +426,12 @@ def _schedule_event( **kwargs: Any, ) -> asyncio.Task: wrapped = self._run_event(coro, event_name, *args, **kwargs) - # Schedules the task - return asyncio.create_task(wrapped, name=f"pycord: {event_name}") + + # Schedule task and store in set to avoid task garbage collection + task = asyncio.create_task(wrapped, name=f"pycord: {event_name}") + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + return task def dispatch(self, event: str, *args: Any, **kwargs: Any) -> None: _log.debug("Dispatching event %s", event)