Skip to content

Commit 0168bef

Browse files
committed
clean up context handling
1 parent db270dc commit 0168bef

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

jupyter_client/client.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import sys
66
import time
77
import typing as t
8-
import weakref
98
from functools import partial
109
from getpass import getpass
1110
from queue import Empty
@@ -94,10 +93,7 @@ class KernelClient(ConnectionFileMixin):
9493
context = Instance(zmq.asyncio.Context)
9594

9695
def _context_default(self) -> zmq.asyncio.Context:
97-
context = zmq.asyncio.Context()
98-
# Use a finalizer to destroy the context.
99-
self._finalizer = weakref.finalize(self, context.destroy)
100-
return context
96+
return zmq.asyncio.Context()
10197

10298
# The classes to use for the various channels
10399
shell_channel_class = Type(ChannelABC)
@@ -116,6 +112,11 @@ def _context_default(self) -> zmq.asyncio.Context:
116112
# flag for whether execute requests should be allowed to call raw_input:
117113
allow_stdin: bool = True
118114

115+
def __del__(self):
116+
"""Clean up the context when garbage collected."""
117+
if not self.channels_running:
118+
self.context.destroy()
119+
119120
# --------------------------------------------------------------------------
120121
# Channel proxy methods
121122
# --------------------------------------------------------------------------

jupyter_client/multikernelmanager.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import socket
77
import typing as t
88
import uuid
9-
import weakref
109

1110
import zmq
1211
from traitlets import Any
@@ -107,15 +106,16 @@ def _starting_kernels(self):
107106

108107
@default("context") # type:ignore[misc]
109108
def _context_default(self) -> zmq.Context:
110-
context = zmq.Context()
111-
# Use a finalizer to destroy the context.
112-
self._finalizer = weakref.finalize(self, context.destroy)
113-
return context
109+
return zmq.Context()
114110

115111
connection_dir = Unicode("")
116112

117113
_kernels = Dict()
118114

115+
def __del__(self):
116+
"""Clean up the context when garbage collected."""
117+
self.context.destroy()
118+
119119
def list_kernel_ids(self) -> t.List[str]:
120120
"""Return a list of the kernel ids of the active kernels."""
121121
# Create a copy so we can iterate over kernels in operations

0 commit comments

Comments
 (0)