Skip to content

Commit 518785b

Browse files
authored
Update typing (#1150)
1 parent 83ab7d0 commit 518785b

File tree

11 files changed

+149
-68
lines changed

11 files changed

+149
-68
lines changed

ipykernel/comm/comm.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ def publish_msg(self, msg_type, data=None, metadata=None, buffers=None, **keys):
3333
if self.kernel is None:
3434
self.kernel = Kernel.instance()
3535

36+
assert self.kernel.session is not None
3637
self.kernel.session.send(
3738
self.kernel.iopub_socket,
3839
msg_type,

ipykernel/datapub.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ def publish_data(self, data):
4848
The data to be published. Think of it as a namespace.
4949
"""
5050
session = self.session
51+
assert session is not None
5152
buffers = serialize_object(
5253
data,
5354
buffer_threshold=session.buffer_threshold,

ipykernel/displayhook.py

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
# Copyright (c) IPython Development Team.
44
# Distributed under the terms of the Modified BSD License.
5+
from __future__ import annotations
56

67
import builtins
78
import sys
9+
import typing as t
810

911
from IPython.core.displayhook import DisplayHook
1012
from jupyter_client.session import Session, extract_header
@@ -61,35 +63,39 @@ class ZMQShellDisplayHook(DisplayHook):
6163
session = Instance(Session, allow_none=True)
6264
pub_socket = Any(allow_none=True)
6365
parent_header = Dict({})
66+
msg: dict[str, t.Any] | None
6467

6568
def set_parent(self, parent):
6669
"""Set the parent for outbound messages."""
6770
self.parent_header = extract_header(parent)
6871

6972
def start_displayhook(self):
7073
"""Start the display hook."""
71-
self.msg = self.session.msg(
72-
"execute_result",
73-
{
74-
"data": {},
75-
"metadata": {},
76-
},
77-
parent=self.parent_header,
78-
)
74+
if self.session:
75+
self.msg = self.session.msg(
76+
"execute_result",
77+
{
78+
"data": {},
79+
"metadata": {},
80+
},
81+
parent=self.parent_header,
82+
)
7983

8084
def write_output_prompt(self):
8185
"""Write the output prompt."""
82-
self.msg["content"]["execution_count"] = self.prompt_count
86+
if self.msg:
87+
self.msg["content"]["execution_count"] = self.prompt_count
8388

8489
def write_format_data(self, format_dict, md_dict=None):
8590
"""Write format data to the message."""
86-
self.msg["content"]["data"] = json_clean(encode_images(format_dict))
87-
self.msg["content"]["metadata"] = md_dict
91+
if self.msg:
92+
self.msg["content"]["data"] = json_clean(encode_images(format_dict))
93+
self.msg["content"]["metadata"] = md_dict
8894

8995
def finish_displayhook(self):
9096
"""Finish up all displayhook activities."""
9197
sys.stdout.flush()
9298
sys.stderr.flush()
93-
if self.msg["content"]["data"]:
99+
if self.msg and self.msg["content"]["data"] and self.session:
94100
self.session.send(self.pub_socket, self.msg, ident=self.topic)
95101
self.msg = None

ipykernel/inprocess/client.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,42 +60,43 @@ def _default_blocking_class(self):
6060
def get_connection_info(self):
6161
"""Get the connection info for the client."""
6262
d = super().get_connection_info()
63-
d["kernel"] = self.kernel
63+
d["kernel"] = self.kernel # type:ignore[assignment]
6464
return d
6565

6666
def start_channels(self, *args, **kwargs):
6767
"""Start the channels on the client."""
6868
super().start_channels()
69-
self.kernel.frontends.append(self)
69+
if self.kernel:
70+
self.kernel.frontends.append(self)
7071

7172
@property
7273
def shell_channel(self):
7374
if self._shell_channel is None:
74-
self._shell_channel = self.shell_channel_class(self)
75+
self._shell_channel = self.shell_channel_class(self) # type:ignore[operator]
7576
return self._shell_channel
7677

7778
@property
7879
def iopub_channel(self):
7980
if self._iopub_channel is None:
80-
self._iopub_channel = self.iopub_channel_class(self)
81+
self._iopub_channel = self.iopub_channel_class(self) # type:ignore[operator]
8182
return self._iopub_channel
8283

8384
@property
8485
def stdin_channel(self):
8586
if self._stdin_channel is None:
86-
self._stdin_channel = self.stdin_channel_class(self)
87+
self._stdin_channel = self.stdin_channel_class(self) # type:ignore[operator]
8788
return self._stdin_channel
8889

8990
@property
9091
def control_channel(self):
9192
if self._control_channel is None:
92-
self._control_channel = self.control_channel_class(self)
93+
self._control_channel = self.control_channel_class(self) # type:ignore[operator]
9394
return self._control_channel
9495

9596
@property
9697
def hb_channel(self):
9798
if self._hb_channel is None:
98-
self._hb_channel = self.hb_channel_class(self)
99+
self._hb_channel = self.hb_channel_class(self) # type:ignore[operator]
99100
return self._hb_channel
100101

101102
# Methods for sending specific messages

ipykernel/inprocess/ipkernel.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ class InProcessKernel(IPythonKernel):
5151
_underlying_iopub_socket = Instance(DummySocket, ())
5252
iopub_thread: IOPubThread = Instance(IOPubThread) # type:ignore[assignment]
5353

54-
shell_stream = Instance(DummySocket, ())
54+
shell_stream = Instance(DummySocket, ()) # type:ignore[arg-type]
5555

5656
@default("iopub_thread")
5757
def _default_iopub_thread(self):
@@ -72,7 +72,8 @@ def __init__(self, **traits):
7272
super().__init__(**traits)
7373

7474
self._underlying_iopub_socket.observe(self._io_dispatch, names=["message_sent"])
75-
self.shell.kernel = self
75+
if self.shell:
76+
self.shell.kernel = self
7677

7778
async def execute_request(self, stream, ident, parent):
7879
"""Override for temporary IO redirection."""
@@ -81,7 +82,8 @@ async def execute_request(self, stream, ident, parent):
8182

8283
def start(self):
8384
"""Override registration of dispatchers for streams."""
84-
self.shell.exit_now = False
85+
if self.shell:
86+
self.shell.exit_now = False
8587

8688
def _abort_queues(self):
8789
"""The in-process kernel doesn't abort requests."""
@@ -99,6 +101,7 @@ def _input_request(self, prompt, ident, parent, password=False):
99101

100102
# Send the input request.
101103
content = json_clean(dict(prompt=prompt, password=password))
104+
assert self.session is not None
102105
msg = self.session.msg("input_request", content, parent)
103106
for frontend in self.frontends:
104107
if frontend.session.session == parent["header"]["session"]:
@@ -132,6 +135,7 @@ def _redirected_io(self):
132135
def _io_dispatch(self, change):
133136
"""Called when a message is sent to the IO socket."""
134137
assert self.iopub_socket.io_thread is not None
138+
assert self.session is not None
135139
ident, msg = self.session.recv(self.iopub_socket.io_thread.socket, copy=False)
136140
for frontend in self.frontends:
137141
frontend.iopub_channel.call_handlers(msg)

ipykernel/inprocess/manager.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ def start_kernel(self, **kwds):
4949

5050
def shutdown_kernel(self):
5151
"""Shutdown the kernel."""
52-
self.kernel.iopub_thread.stop()
53-
self._kill_kernel()
52+
if self.kernel:
53+
self.kernel.iopub_thread.stop()
54+
self._kill_kernel()
5455

5556
def restart_kernel(self, now=False, **kwds):
5657
"""Restart the kernel."""

ipykernel/ipkernel.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def __init__(self, **kwargs):
118118
)
119119

120120
# Initialize the InteractiveShell subclass
121-
self.shell = self.shell_class.instance(
121+
self.shell = self.shell_class.instance( # type:ignore[attr-defined]
122122
parent=self,
123123
profile_dir=self.profile_dir,
124124
user_module=self.user_module,
@@ -206,7 +206,8 @@ def dispatch_debugpy(self, msg):
206206

207207
@property
208208
def banner(self):
209-
return self.shell.banner
209+
if self.shell:
210+
return self.shell.banner
210211

211212
async def poll_stopped_queue(self):
212213
"""Poll the stopped queue."""
@@ -215,7 +216,8 @@ async def poll_stopped_queue(self):
215216

216217
def start(self):
217218
"""Start the kernel."""
218-
self.shell.exit_now = False
219+
if self.shell:
220+
self.shell.exit_now = False
219221
if self.debugpy_stream is None:
220222
self.log.warning("debugpy_stream undefined, debugging will not be enabled")
221223
else:
@@ -231,7 +233,7 @@ def set_parent(self, ident, parent, channel="shell"):
231233
about the parent message.
232234
"""
233235
super().set_parent(ident, parent, channel)
234-
if channel == "shell":
236+
if channel == "shell" and self.shell:
235237
self.shell.set_parent(parent)
236238

237239
def init_metadata(self, parent):
@@ -284,7 +286,8 @@ def _restore_input(self):
284286

285287
@property
286288
def execution_count(self):
287-
return self.shell.execution_count
289+
if self.shell:
290+
return self.shell.execution_count
288291

289292
@execution_count.setter
290293
def execution_count(self, value):
@@ -348,6 +351,7 @@ async def do_execute(
348351
):
349352
"""Handle code execution."""
350353
shell = self.shell # we'll need this a lot here
354+
assert shell is not None
351355

352356
self._forward_input(allow_stdin)
353357

@@ -371,7 +375,7 @@ async def run_cell(*args, **kwargs):
371375
# not just asyncio
372376
preprocessing_exc_tuple = None
373377
try:
374-
transformed_cell = self.shell.transform_cell(code)
378+
transformed_cell = shell.transform_cell(code)
375379
except Exception:
376380
transformed_cell = code
377381
preprocessing_exc_tuple = sys.exc_info()
@@ -488,6 +492,7 @@ def do_complete(self, code, cursor_pos):
488492
cursor_pos = len(code)
489493
line, offset = line_at_cursor(code, cursor_pos)
490494
line_cursor = cursor_pos - offset
495+
assert self.shell is not None
491496
txt, matches = self.shell.complete("", line, line_cursor)
492497
return {
493498
"matches": matches,
@@ -509,6 +514,7 @@ def _experimental_do_complete(self, code, cursor_pos):
509514
if cursor_pos is None:
510515
cursor_pos = len(code)
511516
with _provisionalcompleter():
517+
assert self.shell is not None
512518
raw_completions = self.shell.Completer.completions(code, cursor_pos)
513519
completions = list(_rectify_completions(code, raw_completions))
514520

@@ -548,6 +554,7 @@ def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
548554
reply_content: t.Dict[str, t.Any] = {"status": "ok"}
549555
reply_content["data"] = {}
550556
reply_content["metadata"] = {}
557+
assert self.shell is not None
551558
try:
552559
if release.version_info >= (8,):
553560
# `omit_sections` keyword will be available in IPython 8, see
@@ -581,6 +588,7 @@ def do_history(
581588
unique=False,
582589
):
583590
"""Handle code history."""
591+
assert self.shell is not None
584592
if hist_access_type == "tail":
585593
hist = self.shell.history_manager.get_tail(
586594
n, raw=raw, output=output, include_latest=True
@@ -605,14 +613,16 @@ def do_history(
605613

606614
def do_shutdown(self, restart):
607615
"""Handle kernel shutdown."""
608-
self.shell.exit_now = True
616+
if self.shell:
617+
self.shell.exit_now = True
609618
return dict(status="ok", restart=restart)
610619

611620
def do_is_complete(self, code):
612621
"""Handle an is_complete request."""
613622
transformer_manager = getattr(self.shell, "input_transformer_manager", None)
614623
if transformer_manager is None:
615624
# input_splitter attribute is deprecated
625+
assert self.shell is not None
616626
transformer_manager = self.shell.input_splitter
617627
status, indent_spaces = transformer_manager.check_complete(code)
618628
r = {"status": status}
@@ -628,6 +638,7 @@ def do_apply(self, content, bufs, msg_id, reply_metadata):
628638
from .serialize import serialize_object, unpack_apply_message
629639

630640
shell = self.shell
641+
assert shell is not None
631642
try:
632643
working = shell.user_ns
633644

@@ -652,6 +663,7 @@ def do_apply(self, content, bufs, msg_id, reply_metadata):
652663
for key in ns:
653664
working.pop(key)
654665

666+
assert self.session is not None
655667
result_buf = serialize_object(
656668
result,
657669
buffer_threshold=self.session.buffer_threshold,
@@ -686,7 +698,8 @@ def do_apply(self, content, bufs, msg_id, reply_metadata):
686698

687699
def do_clear(self):
688700
"""Clear the kernel."""
689-
self.shell.reset(False)
701+
if self.shell:
702+
self.shell.reset(False)
690703
return dict(status="ok")
691704

692705

ipykernel/kernelapp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,7 @@ def init_kernel(self):
547547
control_stream = ZMQStream(self.control_socket, self.control_thread.io_loop)
548548
debugpy_stream = ZMQStream(self.debugpy_socket, self.control_thread.io_loop)
549549
self.control_thread.start()
550-
kernel_factory = self.kernel_class.instance
550+
kernel_factory = self.kernel_class.instance # type:ignore[attr-defined]
551551

552552
kernel = kernel_factory(
553553
parent=self,

0 commit comments

Comments
 (0)