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())