Skip to content

Commit caba06b

Browse files
committed
allow using clients as context managers
easier to clean them up
1 parent f093b39 commit caba06b

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

ipyparallel/client/client.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,19 @@ def _setup_profile_dir(self, profile, profile_dir, ipython_dir):
605605
pass
606606
self._cd = None
607607

608+
def __enter__(self):
609+
"""A client can be used as a context manager
610+
611+
which will close the client on exit
612+
613+
.. versionadded: 7.0
614+
"""
615+
return self
616+
617+
def __exit__(self, exc_type, exc_value, traceback):
618+
"""Exiting a client context closes the client"""
619+
self.close()
620+
608621
def _update_engines(self, engines):
609622
"""Update our engines dict and _ids from a dict of the form: {id:uuid}."""
610623
for k, v in iteritems(engines):

ipyparallel/tests/test_cluster.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,9 @@ async def test_start_stop_controller(Cluster):
7373
proc = cluster._controller.process
7474
assert proc.poll() is None
7575
# TODO: wait for connection
76-
client = cluster.connect_client()
77-
assert client.queue_status() == {'unassigned': 0}
78-
client.close()
76+
with cluster.connect_client() as rc:
77+
assert rc.queue_status() == {'unassigned': 0}
78+
7979
await cluster.stop_controller()
8080
assert not proc.poll() is not None
8181
assert cluster._controller is None
@@ -110,19 +110,20 @@ async def test_start_stop_cluster(Cluster, engine_launcher_class):
110110
assert controller is not None
111111
assert len(cluster._engine_sets) == 1
112112

113-
rc = cluster.connect_client()
114-
rc.wait_for_engines(n, timeout=10)
113+
with cluster.connect_client() as rc:
114+
rc.wait_for_engines(n, timeout=10)
115115
await cluster.stop_cluster()
116116
assert cluster._controller is None
117117
assert cluster._engine_sets == {}
118118

119119

120120
@pytest.mark.parametrize("engine_launcher_class", _engine_launcher_classes)
121-
async def test_signal_engines(Cluster, engine_launcher_class):
121+
async def test_signal_engines(request, Cluster, engine_launcher_class):
122122
cluster = Cluster(engine_launcher_class=engine_launcher_class)
123123
await cluster.start_controller()
124124
engine_set_id = await cluster.start_engines(n=3)
125125
rc = cluster.connect_client()
126+
request.addfinalizer(rc.close)
126127
while len(rc) < 3:
127128
await asyncio.sleep(0.1)
128129
# seems to be a problem if we start too soon...

0 commit comments

Comments
 (0)