Skip to content

Commit 64cab58

Browse files
yinghsienwucopybara-github
authored andcommitted
fix: Make __del__ methods more robust in _api_client and client.
Guard `close()` in `_api_client.__del__` to only run if custom `httpx_client` is not set, and wrap `close()` in `client.__del__` with a try-except block to catch any exceptions during finalization. Fixes: #1567 Fixes: #1565 PiperOrigin-RevId: 825620765
1 parent f63a302 commit 64cab58

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

google/genai/_api_client.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1824,11 +1824,17 @@ def __del__(self) -> None:
18241824
"""
18251825

18261826
try:
1827-
self.close()
1827+
# Let users close the custom client explicitly by themselves. Otherwise,
1828+
# close the client when the object is garbage collected.
1829+
if not self._http_options.httpx_client:
1830+
self.close()
18281831
except Exception: # pylint: disable=broad-except
18291832
pass
18301833

18311834
try:
1832-
asyncio.get_running_loop().create_task(self.aclose())
1835+
# Let users close the custom client explicitly by themselves. Otherwise,
1836+
# close the client when the object is garbage collected.
1837+
if not self._http_options.httpx_async_client:
1838+
asyncio.get_running_loop().create_task(self.aclose())
18331839
except Exception: # pylint: disable=broad-except
18341840
pass

google/genai/client.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,4 +397,7 @@ def __exit__(
397397
self.close()
398398

399399
def __del__(self) -> None:
400-
self.close()
400+
try:
401+
self.close()
402+
except Exception:
403+
pass

0 commit comments

Comments
 (0)