Skip to content

Commit a50d602

Browse files
committed
more context cleanup
1 parent 0168bef commit a50d602

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

jupyter_client/client.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import zmq.asyncio
1313
from traitlets import Any
14+
from traitlets import Bool
1415
from traitlets import Instance
1516
from traitlets import Type
1617

@@ -92,7 +93,10 @@ class KernelClient(ConnectionFileMixin):
9293
# The PyZMQ Context to use for communication with the kernel.
9394
context = Instance(zmq.asyncio.Context)
9495

96+
_created_context = Bool(False)
97+
9598
def _context_default(self) -> zmq.asyncio.Context:
99+
self._created_context = True
96100
return zmq.asyncio.Context()
97101

98102
# The classes to use for the various channels
@@ -113,9 +117,16 @@ def _context_default(self) -> zmq.asyncio.Context:
113117
allow_stdin: bool = True
114118

115119
def __del__(self):
116-
"""Clean up the context when garbage collected."""
117-
if not self.channels_running:
120+
if self._created_context and self.context and not self.context.closed:
121+
if self.log:
122+
self.log.debug("Destroying zmq context for %s", self)
118123
self.context.destroy()
124+
try:
125+
super_del = super().__del__
126+
except AttributeError:
127+
pass
128+
else:
129+
super_del()
119130

120131
# --------------------------------------------------------------------------
121132
# Channel proxy methods

jupyter_client/multikernelmanager.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ def create_kernel_manager(*args: Any, **kwargs: Any) -> KernelManager:
9797

9898
context = Instance("zmq.Context")
9999

100+
_created_context = Bool(False)
101+
100102
_pending_kernels = Dict()
101103

102104
@property
@@ -106,15 +108,24 @@ def _starting_kernels(self):
106108

107109
@default("context") # type:ignore[misc]
108110
def _context_default(self) -> zmq.Context:
111+
self._created_context = True
109112
return zmq.Context()
110113

111114
connection_dir = Unicode("")
112115

113116
_kernels = Dict()
114117

115118
def __del__(self):
116-
"""Clean up the context when garbage collected."""
117-
self.context.destroy()
119+
if self._created_context and self.context and not self.context.closed:
120+
if self.log:
121+
self.log.debug("Destroying zmq context for %s", self)
122+
self.context.destroy()
123+
try:
124+
super_del = super().__del__
125+
except AttributeError:
126+
pass
127+
else:
128+
super_del()
118129

119130
def list_kernel_ids(self) -> t.List[str]:
120131
"""Return a list of the kernel ids of the active kernels."""

0 commit comments

Comments
 (0)