Skip to content

Commit

Permalink
add Kernel.get_parent_header
Browse files Browse the repository at this point in the history
- deprecate Kernel._parent_header
- move new multi-parent header dict to new Kernel._parent_headers instead of changing what Kernel._parent_header means
  • Loading branch information
minrk committed May 7, 2021
1 parent 317159f commit 1d89505
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 26 deletions.
2 changes: 1 addition & 1 deletion ipykernel/comm/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def _publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys)
self.kernel.session.send(self.kernel.iopub_socket, msg_type,
content,
metadata=json_clean(metadata),
parent=self.kernel._parent_header.get('shell', {}),
parent=self.kernel.get_parent_header("shell"),
ident=self.topic,
buffers=buffers,
)
Expand Down
95 changes: 70 additions & 25 deletions ipykernel/kernelbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,18 @@ def _default_ident(self):

# track associations with current request
_allow_stdin = Bool(False)
_parent_header = Dict({'shell': {}, 'control': {}})
_parent_headers = Dict({"shell": {}, "control": {}})
_parent_ident = Dict({'shell': b'', 'control': b''})

@property
def _parent_header(self):
warnings.warn(
"Kernel._parent_header is deprecated in ipykernel 6. Use .get_parent_header()",
DeprecationWarning,
stacklevel=2,
)
return self.get_parent_header(channel="shell")

# Time to sleep after flushing the stdout/err buffers in each execute
# cycle. While this introduces a hard limit on the minimal latency of the
# execute cycle, it helps prevent output synchronization problems for
Expand Down Expand Up @@ -207,6 +217,23 @@ def __init__(self, **kwargs):

self.control_queue = Queue()

def get_parent_header(self, channel="shell"):
"""Get the parent header associated with a channel.
.. versionadded:: 6
Parameters
----------
channel : str
the name of the channel ('shell' or 'control')
Returns
-------
header : dict
the parent header for the most recent request on the channel.
"""
return self._parent_headers.get(channel, {})

def dispatch_control(self, msg):
self.control_queue.put_nowait(msg)

Expand Down Expand Up @@ -484,18 +511,21 @@ def _publish_execute_input(self, code, parent, execution_count):

def _publish_status(self, status, channel, parent=None):
"""send status (busy/idle) on IOPub"""
self.session.send(self.iopub_socket,
'status',
{'execution_state': status},
parent=parent or self._parent_header[channel],
ident=self._topic('status'),
)
self.session.send(
self.iopub_socket,
"status",
{"execution_state": status},
parent=parent or self.get_parent_header(channel),
ident=self._topic("status"),
)

def _publish_debug_event(self, event):
self.session.send(self.iopub_socket,
'debug_event',
event,
parent=self._parent_header['control'],
ident=self._topic('debug_event')
self.session.send(
self.iopub_socket,
"debug_event",
event,
parent=self.get_parent_header("control"),
ident=self._topic("debug_event"),
)

def set_parent(self, ident, parent, channel='shell'):
Expand All @@ -508,7 +538,7 @@ def set_parent(self, ident, parent, channel='shell'):
on the stdin channel.
"""
self._parent_ident[channel] = ident
self._parent_header[channel] = parent
self._parent_headers[channel] = parent

def send_response(self, stream, msg_or_type, content=None, ident=None,
buffers=None, track=False, header=None, metadata=None, channel='shell'):
Expand All @@ -520,8 +550,17 @@ def send_response(self, stream, msg_or_type, content=None, ident=None,
This relies on :meth:`set_parent` having been called for the current
message.
"""
return self.session.send(stream, msg_or_type, content, self._parent_header[channel],
ident, buffers, track, header, metadata)
return self.session.send(
stream,
msg_or_type,
content,
self.get_parent_header(channel),
ident,
buffers,
track,
header,
metadata,
)

def init_metadata(self, parent):
"""Initialize metadata.
Expand Down Expand Up @@ -630,7 +669,7 @@ async def inspect_request(self, stream, ident, parent):
content.get('detail_level', 0),
)
if inspect.isawaitable(reply_content):
reply_content = await reply_content
reply_content = await reply_content

# Before we send this object over, we scrub it for JSON usage
reply_content = json_clean(reply_content)
Expand Down Expand Up @@ -878,11 +917,16 @@ def getpass(self, prompt='', stream=None):
)
if stream is not None:
import warnings
warnings.warn("The `stream` parameter of `getpass.getpass` will have no effect when using ipykernel",
UserWarning, stacklevel=2)
return self._input_request(prompt,
self._parent_ident['shell'],
self._parent_header['shell'],

warnings.warn(
"The `stream` parameter of `getpass.getpass` will have no effect when using ipykernel",
UserWarning,
stacklevel=2,
)
return self._input_request(
prompt,
self._parent_ident["shell"],
self.get_parent_header("shell"),
password=True,
)

Expand All @@ -897,9 +941,10 @@ def raw_input(self, prompt=''):
raise StdinNotImplementedError(
"raw_input was called, but this frontend does not support input requests."
)
return self._input_request(str(prompt),
self._parent_ident['shell'],
self._parent_header['shell'],
return self._input_request(
str(prompt),
self._parent_ident["shell"],
self.get_parent_header("shell"),
password=False,
)

Expand Down Expand Up @@ -944,7 +989,7 @@ def _input_request(self, prompt, ident, parent, password=False):
raise KeyboardInterrupt("Interrupted by user") from None
except Exception as e:
self.log.warning("Invalid Message:", exc_info=True)

try:
value = reply["content"]["value"]
except Exception:
Expand Down

0 comments on commit 1d89505

Please sign in to comment.