Skip to content

Commit f2ae6e5

Browse files
committed
Add finalizer to Connection
1 parent 81702c9 commit f2ae6e5

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

python/hopsworks_common/connection.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import re
2222
import sys
2323
import warnings
24+
import weakref
2425
from typing import Any, Optional
2526

2627
from hopsworks_common import client, usage, util, version
@@ -351,6 +352,7 @@ def connect(self) -> None:
351352
"""
352353
client.stop()
353354
self._connected = True
355+
finalizer = weakref.finalize(self, self.close)
354356
try:
355357
# determine engine, needed to init client
356358
if (self._engine is not None and self._engine.lower() == "spark") or (
@@ -413,6 +415,7 @@ def connect(self) -> None:
413415
self._provide_project()
414416
except (TypeError, ConnectionError):
415417
self._connected = False
418+
finalizer.detach()
416419
raise
417420

418421
self._check_compatibility()
@@ -446,7 +449,7 @@ def close(self) -> None:
446449
This will clean up any materialized certificates on the local file system of
447450
external environments such as AWS SageMaker.
448451
449-
Usage is recommended but optional.
452+
Usage is optional.
450453
451454
!!! example
452455
```python
@@ -455,6 +458,9 @@ def close(self) -> None:
455458
conn.close()
456459
```
457460
"""
461+
if not self._connected:
462+
return # the connection is already closed
463+
458464
from hsfs import engine
459465

460466
if OpenSearchClientSingleton._instance:

0 commit comments

Comments
 (0)