Skip to content

Commit

Permalink
Merge branch 'main' into dont-raise-error-in-qt-loop
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Jan 8, 2023
2 parents 9bc06be + 4f0e252 commit ec39463
Show file tree
Hide file tree
Showing 18 changed files with 83 additions and 61 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ repos:
- id: mdformat

- repo: https://github.com/psf/black
rev: 22.10.0
rev: 22.12.0
hooks:
- id: black

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.189
rev: v0.0.215
hooks:
- id: ruff
args: ["--fix"]
3 changes: 2 additions & 1 deletion ipykernel/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ def get_connection_file(app=None):
from ipykernel.kernelapp import IPKernelApp

if not IPKernelApp.initialized():
raise RuntimeError("app not specified, and not in a running Kernel")
msg = "app not specified, and not in a running Kernel"
raise RuntimeError(msg)

app = IPKernelApp.instance()
return filefind(app.connection_file, [".", app.connection_dir])
Expand Down
19 changes: 10 additions & 9 deletions ipykernel/eventloops.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,8 +473,8 @@ def set_qt_api_env_from_gui(gui):
}
if loaded is not None and gui != 'qt':
if qt_env2gui[loaded] != gui:
print(f'Cannot switch Qt versions for this session; you must use {qt_env2gui[loaded]}.')
return
msg = f'Cannot switch Qt versions for this session; must use {qt_env2gui[loaded]}.'
raise ImportError(msg)

if qt_api is not None and gui != 'qt':
if qt_env2gui[qt_api] != gui:
Expand Down Expand Up @@ -513,8 +513,8 @@ def set_qt_api_env_from_gui(gui):
if 'QT_API' in os.environ.keys():
del os.environ['QT_API']
else:
print(f'Unrecognized Qt version: {gui}. Should be "qt5", "qt6", or "qt".')
return
msg = f'Unrecognized Qt version: {gui}. Should be "qt4", "qt5", "qt6", or "qt".'
raise ValueError(msg)

# Do the actual import now that the environment variable is set to make sure it works.
try:
Expand All @@ -530,9 +530,8 @@ def set_qt_api_env_from_gui(gui):
def make_qt_app_for_kernel(gui, kernel):
"""Sets the `QT_API` environment variable if it isn't already set."""
if hasattr(kernel, 'app'):
# Kernel is already running a Qt event loop, so there's no need to
# create another app for it.
return
msg = 'Kernel already running a Qt event loop.'
raise RuntimeError(msg)

set_qt_api_env_from_gui(gui)

Expand All @@ -556,10 +555,11 @@ def enable_gui(gui, kernel=None):
if Application.initialized():
kernel = getattr(Application.instance(), "kernel", None)
if kernel is None:
raise RuntimeError(
msg = (
"You didn't specify a kernel,"
" and no IPython Application with a kernel appears to be running."
)
raise RuntimeError(msg)
if gui is None:
# User wants to turn off integration; clear any evidence if Qt was the last one.
if hasattr(kernel, 'app'):
Expand All @@ -571,7 +571,8 @@ def enable_gui(gui, kernel=None):

loop = loop_map[gui]
if loop and kernel.eventloop is not None and kernel.eventloop is not loop:
raise RuntimeError("Cannot activate multiple GUI eventloops")
msg = "Cannot activate multiple GUI eventloops"
raise RuntimeError(msg)
kernel.eventloop = loop
# We set `eventloop`; the function the user chose is executed in `Kernel.enter_eventloop`, thus
# any exceptions raised during the event loop will not be shown in the client.
3 changes: 2 additions & 1 deletion ipykernel/inprocess/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ def call_handlers(self, msg):
Subclasses should override this method to handle incoming messages.
"""
raise NotImplementedError("call_handlers must be defined in a subclass.")
msg = "call_handlers must be defined in a subclass."
raise NotImplementedError(msg)

def flush(self, timeout=1.0):
"""Flush the channel."""
Expand Down
9 changes: 6 additions & 3 deletions ipykernel/inprocess/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ def history(self, raw=True, output=False, hist_access_type="range", **kwds):
def shutdown(self, restart=False):
"""Handle shutdown."""
# FIXME: What to do here?
raise NotImplementedError("Cannot shutdown in-process kernel")
msg = "Cannot shutdown in-process kernel"
raise NotImplementedError(msg)

def kernel_info(self):
"""Request kernel info."""
Expand All @@ -175,7 +176,8 @@ def comm_info(self, target_name=None):
def input(self, string):
"""Handle kernel input."""
if self.kernel is None:
raise RuntimeError("Cannot send input reply. No kernel exists.")
msg = "Cannot send input reply. No kernel exists."
raise RuntimeError(msg)
self.kernel.raw_input_str = string

def is_complete(self, code):
Expand All @@ -188,7 +190,8 @@ def _dispatch_to_kernel(self, msg):
"""Send a message to the kernel and handle a reply."""
kernel = self.kernel
if kernel is None:
raise RuntimeError("Cannot send request. No kernel exists.")
msg = "Cannot send request. No kernel exists."
raise RuntimeError(msg)

stream = kernel.shell_stream
self.session.send(stream, msg)
Expand Down
6 changes: 4 additions & 2 deletions ipykernel/inprocess/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,13 @@ def _kill_kernel(self):

def interrupt_kernel(self):
"""Interrupt the kernel."""
raise NotImplementedError("Cannot interrupt in-process kernel.")
msg = "Cannot interrupt in-process kernel."
raise NotImplementedError(msg)

def signal_kernel(self, signum):
"""Send a signal to the kernel."""
raise NotImplementedError("Cannot signal in-process kernel.")
msg = "Cannot signal in-process kernel."
raise NotImplementedError(msg)

def is_alive(self):
"""Test if the kernel is alive."""
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/inprocess/tests/test_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from io import StringIO

import pytest
from IPython.utils.io import capture_output
from IPython.utils.io import capture_output # type:ignore[attr-defined]
from jupyter_client.session import Session

from ipykernel.inprocess.blocking import BlockingInProcessKernelClient
Expand Down
15 changes: 10 additions & 5 deletions ipykernel/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,8 @@ def fileno(self):
if getattr(self, "_original_stdstream_copy", None) is not None:
return self._original_stdstream_copy
else:
raise io.UnsupportedOperation("fileno")
msg = "fileno"
raise io.UnsupportedOperation(msg)

def _watch_pipe_fd(self):
"""
Expand Down Expand Up @@ -415,7 +416,8 @@ def __init__(
if hasattr(echo, "read") and hasattr(echo, "write"):
self.echo = echo
else:
raise ValueError("echo argument must be a file like object")
msg = "echo argument must be a file like object"
raise ValueError(msg)

def isatty(self):
"""Return a bool indicating whether this is an 'interactive' stream.
Expand Down Expand Up @@ -540,7 +542,8 @@ def write(self, string: str) -> Optional[int]: # type:ignore[override]
"""

if not isinstance(string, str):
raise TypeError(f"write() argument must be str, not {type(string)}")
msg = f"write() argument must be str, not {type(string)}"
raise TypeError(msg)

if self.echo is not None:
try:
Expand All @@ -550,7 +553,8 @@ def write(self, string: str) -> Optional[int]: # type:ignore[override]
print(f"Write failed: {e}", file=sys.__stderr__)

if self.pub_thread is None:
raise ValueError("I/O operation on closed file")
msg = "I/O operation on closed file"
raise ValueError(msg)
else:

is_child = not self._is_master_process()
Expand All @@ -573,7 +577,8 @@ def write(self, string: str) -> Optional[int]: # type:ignore[override]
def writelines(self, sequence):
"""Write lines to the stream."""
if self.pub_thread is None:
raise ValueError("I/O operation on closed file")
msg = "I/O operation on closed file"
raise ValueError(msg)
else:
for string in sequence:
self.write(string)
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/ipkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from .zmqshell import ZMQInteractiveShell

try:
from IPython.core.interactiveshell import _asyncio_runner
from IPython.core.interactiveshell import _asyncio_runner # type:ignore[attr-defined]
except ImportError:
_asyncio_runner = None

Expand Down
3 changes: 2 additions & 1 deletion ipykernel/jsonutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,11 @@ def json_clean(obj): # pragma: no cover
nkeys = len(obj)
nkeys_collapsed = len(set(map(str, obj)))
if nkeys != nkeys_collapsed:
raise ValueError(
msg = (
"dict cannot be safely converted to JSON: "
"key collision would lead to dropped values"
)
raise ValueError(msg)
# If all OK, proceed by making the new dict that will be json-safe
out = {}
for k, v in obj.items():
Expand Down
22 changes: 11 additions & 11 deletions ipykernel/kernelapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from logging import StreamHandler

import zmq
from IPython.core.application import (
from IPython.core.application import ( # type:ignore[attr-defined]
BaseIPythonApplication,
base_aliases,
base_flags,
Expand Down Expand Up @@ -88,12 +88,12 @@
)

# inherit flags&aliases for any IPython shell apps
kernel_aliases.update(shell_aliases)
kernel_aliases.update(shell_aliases) # type:ignore[arg-type]
kernel_flags.update(shell_flags)

# inherit flags&aliases for Sessions
kernel_aliases.update(session_aliases)
kernel_flags.update(session_flags)
kernel_aliases.update(session_aliases) # type:ignore[arg-type]
kernel_flags.update(session_flags) # type:ignore[arg-type]

_ctrl_c_message = """\
NOTE: When using the `ipython kernel` entry point, Ctrl-C will not work.
Expand All @@ -114,8 +114,8 @@ class IPKernelApp(BaseIPythonApplication, InteractiveShellApp, ConnectionFileMix
"""The IPYKernel application class."""

name = "ipython-kernel"
aliases = Dict(kernel_aliases)
flags = Dict(kernel_flags)
aliases = Dict(kernel_aliases) # type:ignore[assignment]
flags = Dict(kernel_flags) # type:ignore[assignment]
classes = [IPythonKernel, ZMQInteractiveShell, ProfileDir, Session]
# the kernel class, as an importstring
kernel_class = Type(
Expand Down Expand Up @@ -429,7 +429,7 @@ def log_connection_info(self):
self.log.info(line)
# also raw print to the terminal if no parent_handle (`ipython kernel`)
# unless log-level is CRITICAL (--quiet)
if not self.parent_handle and self.log_level < logging.CRITICAL:
if not self.parent_handle and int(self.log_level) < logging.CRITICAL:
print(_ctrl_c_message, file=sys.__stdout__)
for line in lines:
print(line, file=sys.__stdout__)
Expand Down Expand Up @@ -658,9 +658,9 @@ def init_pdb(self):

if hasattr(debugger, "InterruptiblePdb"):
# Only available in newer IPython releases:
debugger.Pdb = debugger.InterruptiblePdb
pdb.Pdb = debugger.Pdb # type:ignore[misc]
pdb.set_trace = debugger.set_trace
debugger.Pdb = debugger.InterruptiblePdb # type:ignore
pdb.Pdb = debugger.Pdb # type:ignore
pdb.set_trace = debugger.set_trace # type:ignore[assignment]

@catch_config_error
def initialize(self, argv=None):
Expand All @@ -687,7 +687,7 @@ def initialize(self, argv=None):
except Exception:
# Catch exception when initializing signal fails, eg when running the
# kernel on a separate thread
if self.log_level < logging.CRITICAL:
if int(self.log_level) < logging.CRITICAL:
self.log.error("Unable to initialize signal:", exc_info=True)
self.init_kernel()
# shell init steps
Expand Down
18 changes: 8 additions & 10 deletions ipykernel/kernelbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -1146,9 +1146,8 @@ def _send_abort_reply(self, stream, msg, idents):
def _no_raw_input(self):
"""Raise StdinNotImplementedError if active frontend doesn't support
stdin."""
raise StdinNotImplementedError(
"raw_input was called, but this frontend does not support stdin."
)
msg = "raw_input was called, but this frontend does not support stdin."
raise StdinNotImplementedError(msg)

def getpass(self, prompt="", stream=None):
"""Forward getpass to frontends
Expand All @@ -1158,9 +1157,8 @@ def getpass(self, prompt="", stream=None):
StdinNotImplementedError if active frontend doesn't support stdin.
"""
if not self._allow_stdin:
raise StdinNotImplementedError(
"getpass was called, but this frontend does not support input requests."
)
msg = "getpass was called, but this frontend does not support input requests."
raise StdinNotImplementedError(msg)
if stream is not None:
import warnings

Expand All @@ -1184,9 +1182,8 @@ def raw_input(self, prompt=""):
StdinNotImplementedError if active frontend doesn't support stdin.
"""
if not self._allow_stdin:
raise StdinNotImplementedError(
"raw_input was called, but this frontend does not support input requests."
)
msg = "raw_input was called, but this frontend does not support input requests."
raise StdinNotImplementedError(msg)
return self._input_request(
str(prompt),
self._parent_ident["shell"],
Expand Down Expand Up @@ -1229,7 +1226,8 @@ def _input_request(self, prompt, ident, parent, password=False):
break
except KeyboardInterrupt:
# re-raise KeyboardInterrupt, to truncate traceback
raise KeyboardInterrupt("Interrupted by user") from None
msg = "Interrupted by user"
raise KeyboardInterrupt(msg) from None
except Exception:
self.log.warning("Invalid Message:", exc_info=True)

Expand Down
3 changes: 2 additions & 1 deletion ipykernel/parentpoller.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ def __init__(self, interrupt_handle=None, parent_handle=None):
assert interrupt_handle or parent_handle
super().__init__()
if ctypes is None:
raise ImportError("ParentPollerWindows requires ctypes")
msg = "ParentPollerWindows requires ctypes"
raise ImportError(msg)
self.daemon = True
self.interrupt_handle = interrupt_handle
self.parent_handle = parent_handle
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/tests/test_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ def _print_and_exit(sig, frame):


def _start_children():
ip = IPython.get_ipython()
ip = IPython.get_ipython() # type:ignore[attr-defined]
ns = ip.user_ns

cmd = [sys.executable, "-c", f"from {__name__} import _child; _child()"]
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/tests/test_zmq_shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def test_zmq_interactive_shell(kernel):

with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
shell.data_pub_class = MagicMock()
shell.data_pub_class = MagicMock() # type:ignore
shell.data_pub
shell.kernel = kernel
shell.set_next_input("hi")
Expand Down
3 changes: 2 additions & 1 deletion ipykernel/trio_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ def interrupt(self, signum, frame):
if self._cell_cancel_scope:
self._cell_cancel_scope.cancel()
else:
raise Exception("Kernel interrupted but no cell is running")
msg = "Kernel interrupted but no cell is running"
raise Exception(msg)

def run(self):
"""Run the loop."""
Expand Down
Loading

0 comments on commit ec39463

Please sign in to comment.