Skip to content

Commit 40d4048

Browse files
committed
Add finalizer to Connection
1 parent a476f76 commit 40d4048

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

python/hopsworks/connection.py

+11-5
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
@@ -241,6 +242,7 @@ def connect(self):
241242
"""
242243
client.stop()
243244
self._connected = True
245+
finalizer = weakref.finalize(self, self.close)
244246
try:
245247
# init client
246248
if client.base.Client.REST_ENDPOINT not in os.environ:
@@ -263,6 +265,7 @@ def connect(self):
263265
self._variable_api = variable_api.VariableApi()
264266
except (TypeError, ConnectionError):
265267
self._connected = False
268+
finalizer.detach()
266269
raise
267270
print(
268271
"Connected. Call `.close()` to terminate connection gracefully.",
@@ -278,7 +281,7 @@ def close(self):
278281
This will clean up any materialized certificates on the local file system of
279282
external environments such as AWS SageMaker.
280283
281-
Usage is recommended but optional.
284+
Usage is optional.
282285
"""
283286
from hsfs import client as hsfs_client
284287
from hsfs import engine as hsfs_engine
@@ -299,6 +302,9 @@ def close(self):
299302
except: # noqa: E722
300303
pass
301304

305+
if not self._connected:
306+
return # the connection is already closed
307+
302308
client.stop()
303309
self._connected = False
304310

0 commit comments

Comments
 (0)