Skip to content

Commit

Permalink
Support with keyword in session (#451)
Browse files Browse the repository at this point in the history
This PR enables with keyword in session, which can automatically release resourced when the context manager exits.
Moreover, use with will automatically set the session as the default session.

Two simple test cases has been added that can fully demonstrate its usage.
  • Loading branch information
siyuan0322 committed Jun 29, 2021
1 parent 9e99de7 commit e76c81d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
28 changes: 28 additions & 0 deletions python/graphscope/client/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,10 @@ def info(self):
info["engine_config"] = self._engine_config
return info

@property
def closed(self):
return self._closed

def eager(self):
return self._config_params["mode"] == "eager"

Expand Down Expand Up @@ -781,6 +785,30 @@ def __del__(self):
except Exception: # pylint: disable=broad-except
pass

def _check_closed(self, msg=None):
"""Internal: raise a ValueError if session is closed"""
if self.closed:
raise ValueError("Operation on closed session." if msg is None else msg)

# Context manager
def __enter__(self):
"""Context management protocol.
Returns self and register self as default session.
"""
self._check_closed()
self.as_default()
return self

def __exit__(self, type, value, traceback):
"""Deregister self from the default session,
close the session and release the resources, ignore all exceptions in close().
"""
try:
self._deregister_default()
self.close()
except Exception:
pass

def as_default(self):
"""Obtain a context manager that make this object as default session.
Expand Down
10 changes: 10 additions & 0 deletions python/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,13 @@ def test_border_cases():
"e0": "twitter_property_e_0#header_row=true",
}
)


def test_with():
with graphscope.session(cluster_type="hosts") as sess:
assert graphscope.get_default_session() == sess

sess = graphscope.session(cluster_type="hosts")
with sess:
pass
assert sess.info["status"] == "closed"

0 comments on commit e76c81d

Please sign in to comment.