Skip to content

Commit d5c3ff0

Browse files
authored
Add finalizer to Connection (#242)
1 parent bdcdf69 commit d5c3ff0

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

python/hsml/connection.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#
1616

1717
import os
18+
import weakref
1819

1920
from hsml import client
2021
from hsml.core import model_api, model_registry_api, model_serving_api
@@ -165,6 +166,7 @@ def connect(self):
165166
```
166167
"""
167168
self._connected = True
169+
finalizer = weakref.finalize(self, self.close)
168170
try:
169171
# init client
170172
if client.hopsworks.base.Client.REST_ENDPOINT not in os.environ:
@@ -185,6 +187,7 @@ def connect(self):
185187
self._model_serving_api.load_default_configuration() # istio client, default resources,...
186188
except (TypeError, ConnectionError):
187189
self._connected = False
190+
finalizer.detach()
188191
raise
189192
print("Connected. Call `.close()` to terminate connection gracefully.")
190193

@@ -194,8 +197,10 @@ def close(self):
194197
This will clean up any materialized certificates on the local file system of
195198
external environments.
196199
197-
Usage is recommended but optional.
200+
Usage is optional.
198201
"""
202+
if not self._connected:
203+
return # the connection is already closed
199204
client.stop()
200205
self._model_api = None
201206
self._connected = False

0 commit comments

Comments
 (0)