From 73a5616811b538dd5cf52ed79c9bbce29021bee1 Mon Sep 17 00:00:00 2001 From: deedy5 <65482418+deedy5@users.noreply.github.com> Date: Sat, 6 Apr 2024 15:55:22 +0300 Subject: [PATCH] AsyncDDGS|DDGS.__del__(): improve logic and add check - if hasattr(self, "_asession") --- duckduckgo_search/duckduckgo_search.py | 6 +++--- duckduckgo_search/duckduckgo_search_async.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/duckduckgo_search/duckduckgo_search.py b/duckduckgo_search/duckduckgo_search.py index f2f11a9..4bdb778 100644 --- a/duckduckgo_search/duckduckgo_search.py +++ b/duckduckgo_search/duckduckgo_search.py @@ -40,12 +40,12 @@ def __exit__( self._close_session() def __del__(self) -> None: - if self._asession._closed is False: - self._close_session() + self._close_session() def _close_session(self) -> None: """Close the curl-cffi async session.""" - self._run_async_in_thread(self._asession.close()) + if hasattr(self, "_asession") and self._asession._closed is False: + self._run_async_in_thread(self._asession.close()) def _run_async_in_thread(self, coro: Awaitable[Any]) -> Any: """Runs an async coroutine in a separate thread.""" diff --git a/duckduckgo_search/duckduckgo_search_async.py b/duckduckgo_search/duckduckgo_search_async.py index 0ea8fcc..92f1288 100644 --- a/duckduckgo_search/duckduckgo_search_async.py +++ b/duckduckgo_search/duckduckgo_search_async.py @@ -77,10 +77,10 @@ async def __aexit__( exc_val: Optional[BaseException] = None, exc_tb: Optional[TracebackType] = None, ) -> None: - await self._asession.close() + await self._asession.__aexit__(exc_type, exc_val, exc_tb) def __del__(self) -> None: - if self._asession._closed is False: + if hasattr(self, "_asession") and self._asession._closed is False: with suppress(RuntimeError, RuntimeWarning): asyncio.create_task(self._asession.close())