Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ repos:
- id: black

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.207
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,9 +473,8 @@ def set_qt_api_env_from_gui(gui):
}
if loaded is not None and gui != 'qt':
if qt_env2gui[loaded] != gui:
raise ImportError(
f'Cannot switch Qt versions for this session; must use {qt_env2gui[loaded]}.'
)
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 @@ -526,9 +525,8 @@ def set_qt_api_env_from_gui(gui):
if 'QT_API' in os.environ.keys():
del os.environ['QT_API']
else:
raise ValueError(
f'Unrecognized Qt version: {gui}. Should be "qt4", "qt5", "qt6", or "qt".'
)
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 @@ -543,7 +541,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'):
raise RuntimeError('Kernel already running a Qt event loop.')
msg = 'Kernel already running a Qt event loop.'
raise RuntimeError(msg)

set_qt_api_env_from_gui(gui)
# This import is guaranteed to work now:
Expand All @@ -566,10 +565,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 @@ -581,7 +581,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
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
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
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
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
6 changes: 4 additions & 2 deletions ipykernel/zmqshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,8 @@ def less(self, arg_s):

Files ending in .py are syntax-highlighted."""
if not arg_s:
raise UsageError("Missing filename.")
msg = "Missing filename."
raise UsageError(msg)

if arg_s.endswith(".py"):
assert self.shell is not None
Expand Down Expand Up @@ -628,7 +629,8 @@ def system_piped(self, cmd):
# pexpect or pipes to read from. Users can always just call
# os.system() or use ip.system=ip.system_raw
# if they really want a background process.
raise OSError("Background processes not supported.")
msg = "Background processes not supported."
raise OSError(msg)

# we explicitly do NOT return the subprocess status code, because
# a non-None value would trigger :func:`sys.displayhook` calls.
Expand Down
8 changes: 5 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ dependencies = ["mypy>=0.990"]
test = "mypy --install-types --non-interactive {args:.}"

[tool.hatch.envs.lint]
dependencies = ["black==22.12.0", "mdformat>0.7", "ruff==0.0.207"]
dependencies = ["black==22.12.0", "mdformat>0.7", "ruff==0.0.215"]
detached = true
[tool.hatch.envs.lint.scripts]
style = [
Expand Down Expand Up @@ -208,7 +208,7 @@ target-version = ["py37"]
target-version = "py37"
line-length = 100
select = [
"A", "B", "C", "E", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
"A", "B", "C", "E", "EM", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
"UP", "W", "YTT",
]
ignore = [
Expand Down Expand Up @@ -261,7 +261,8 @@ unfixable = [
# B007 Loop control variable `i` not used within the loop body.
# N802 Function name `assertIn` should be lowercase
# F841 Local variable `t` is assigned to but never used
"ipykernel/tests/*" = ["B011", "F841", "C408", "E402", "T201", "B007", "N802", "F841"]
# EM101 Exception must not use a string literal, assign to variable first
"ipykernel/tests/*" = ["B011", "F841", "C408", "E402", "T201", "B007", "N802", "F841", "EM101", "EM102"]

[tool.interrogate]
ignore-init-module=true
Expand All @@ -275,3 +276,4 @@ exclude = ["docs", "*/tests"]

[tool.check-wheel-contents]
toplevel = ["ipykernel/", "ipykernel_launcher.py"]
ignore = ["W002"]