Skip to content

Commit 2606795

Browse files
authored
Add finalizer to Connection (#366)
* Add finalizer to Connection * Ruff fix
1 parent a476f76 commit 2606795

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

python/hopsworks/connection.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616

1717
import os
1818
import re
19-
import warnings
2019
import sys
20+
import warnings
21+
import weakref
2122

22-
from requests.exceptions import ConnectionError
23-
24-
from hopsworks.decorators import connected, not_connected
2523
from hopsworks import client, version
2624
from hopsworks.core import project_api, secret_api, variable_api
25+
from hopsworks.decorators import connected, not_connected
26+
from requests.exceptions import ConnectionError
27+
2728

2829
HOPSWORKS_PORT_DEFAULT = 443
2930
HOSTNAME_VERIFICATION_DEFAULT = True
@@ -210,7 +211,8 @@ def _check_compatibility(self):
210211
warnings.warn(
211212
"The installed hopsworks client version {0} may not be compatible with the connected Hopsworks backend version {1}. \nTo ensure compatibility please install the latest bug fix release matching the minor version of your backend ({2}) by running 'pip install hopsworks=={2}.*'".format(
212213
client_version, backend_version, major_minor_backend
213-
)
214+
),
215+
stacklevel=1,
214216
)
215217
sys.stderr.flush()
216218

@@ -241,6 +243,7 @@ def connect(self):
241243
"""
242244
client.stop()
243245
self._connected = True
246+
finalizer = weakref.finalize(self, self.close)
244247
try:
245248
# init client
246249
if client.base.Client.REST_ENDPOINT not in os.environ:
@@ -263,6 +266,7 @@ def connect(self):
263266
self._variable_api = variable_api.VariableApi()
264267
except (TypeError, ConnectionError):
265268
self._connected = False
269+
finalizer.detach()
266270
raise
267271
print(
268272
"Connected. Call `.close()` to terminate connection gracefully.",
@@ -278,7 +282,7 @@ def close(self):
278282
This will clean up any materialized certificates on the local file system of
279283
external environments such as AWS SageMaker.
280284
281-
Usage is recommended but optional.
285+
Usage is optional.
282286
"""
283287
from hsfs import client as hsfs_client
284288
from hsfs import engine as hsfs_engine
@@ -299,6 +303,9 @@ def close(self):
299303
except: # noqa: E722
300304
pass
301305

306+
if not self._connected:
307+
return # the connection is already closed
308+
302309
client.stop()
303310
self._connected = False
304311

0 commit comments

Comments
 (0)