Skip to content

Commit 717d36e

Browse files
authored
Adopt more ruff rules (#924)
* more linting * typing * fix bug * fix json util test
1 parent 666eab0 commit 717d36e

21 files changed

+161
-126
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ repos:
3535
- id: black
3636

3737
- repo: https://github.com/charliermarsh/ruff-pre-commit
38-
rev: v0.0.221
38+
rev: v0.0.236
3939
hooks:
4040
- id: ruff
4141
args: ["--fix"]

jupyter_client/channels.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def unpause(self) -> None:
159159

160160
def is_beating(self) -> bool:
161161
"""Is the heartbeat running and responsive (and not paused)."""
162-
if self.is_alive() and not self._pause and self._beating:
162+
if self.is_alive() and not self._pause and self._beating: # noqa
163163
return True
164164
else:
165165
return False
@@ -290,7 +290,8 @@ def __init__(self, socket: zmq.asyncio.Socket, session: Session, loop: t.Any = N
290290
Unused here, for other implementations
291291
"""
292292
if not isinstance(socket, zmq.asyncio.Socket):
293-
raise ValueError('Socket must be asyncio')
293+
msg = 'Socket must be asyncio'
294+
raise ValueError(msg)
294295
super().__init__(socket, session)
295296

296297
async def _recv(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: # type:ignore[override]

jupyter_client/client.py

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,8 @@ async def _async_wait_for_ready(self, timeout: t.Optional[float] = None) -> None
195195
break
196196

197197
if not await self._async_is_alive():
198-
raise RuntimeError("Kernel died before replying to kernel_info")
198+
msg = "Kernel died before replying to kernel_info"
199+
raise RuntimeError(msg)
199200

200201
# Check if current time is ready check time plus timeout
201202
if time.time() > abs_timeout:
@@ -223,7 +224,8 @@ async def _async_recv_reply(
223224
else:
224225
reply = await self._async_get_shell_msg(timeout=timeout)
225226
except Empty as e:
226-
raise TimeoutError("Timeout waiting for reply") from e
227+
msg = "Timeout waiting for reply"
228+
raise TimeoutError(msg) from e
227229
if reply["parent_header"].get("msg_id") != msg_id:
228230
# not my reply, someone may have forgotten to retrieve theirs
229231
continue
@@ -232,13 +234,10 @@ async def _async_recv_reply(
232234
async def _stdin_hook_default(self, msg: t.Dict[str, t.Any]) -> None:
233235
"""Handle an input request"""
234236
content = msg["content"]
235-
if content.get("password", False):
236-
prompt = getpass
237-
else:
238-
prompt = input # type: ignore
237+
prompt = getpass if content.get("password", False) else input
239238

240239
try:
241-
raw_data = prompt(content["prompt"])
240+
raw_data = prompt(content["prompt"]) # type:ignore[operator]
242241
except EOFError:
243242
# turn EOFError into EOF character
244243
raw_data = "\x04"
@@ -475,11 +474,13 @@ async def _async_execute_interactive(
475474
The reply message for this request
476475
"""
477476
if not self.iopub_channel.is_alive():
478-
raise RuntimeError("IOPub channel must be running to receive output")
477+
emsg = "IOPub channel must be running to receive output"
478+
raise RuntimeError(emsg)
479479
if allow_stdin is None:
480480
allow_stdin = self.allow_stdin
481481
if allow_stdin and not self.stdin_channel.is_alive():
482-
raise RuntimeError("stdin channel must be running to allow input")
482+
emsg = "stdin channel must be running to allow input"
483+
raise RuntimeError(emsg)
483484
msg_id = await ensure_async(
484485
self.execute(
485486
code,
@@ -492,20 +493,19 @@ async def _async_execute_interactive(
492493
)
493494
if stdin_hook is None:
494495
stdin_hook = self._stdin_hook_default
495-
if output_hook is None:
496-
# detect IPython kernel
497-
if "IPython" in sys.modules:
498-
from IPython import get_ipython
499-
500-
ip = get_ipython()
501-
in_kernel = getattr(ip, "kernel", False)
502-
if in_kernel:
503-
output_hook = partial(
504-
self._output_hook_kernel,
505-
ip.display_pub.session,
506-
ip.display_pub.pub_socket,
507-
ip.display_pub.parent_header,
508-
)
496+
# detect IPython kernel
497+
if output_hook is None and "IPython" in sys.modules:
498+
from IPython import get_ipython
499+
500+
ip = get_ipython()
501+
in_kernel = getattr(ip, "kernel", False)
502+
if in_kernel:
503+
output_hook = partial(
504+
self._output_hook_kernel,
505+
ip.display_pub.session,
506+
ip.display_pub.pub_socket,
507+
ip.display_pub.parent_header,
508+
)
509509
if output_hook is None:
510510
# default: redisplay plain-text outputs
511511
output_hook = self._output_hook_default
@@ -532,7 +532,8 @@ async def _async_execute_interactive(
532532
timeout_ms = int(1000 * timeout)
533533
events = dict(poller.poll(timeout_ms))
534534
if not events:
535-
raise TimeoutError("Timeout waiting for output")
535+
emsg = "Timeout waiting for output"
536+
raise TimeoutError(emsg)
536537
if stdin_socket in events:
537538
req = await ensure_async(self.stdin_channel.get_msg(timeout=0))
538539
res = stdin_hook(req)
@@ -747,10 +748,7 @@ def comm_info(self, target_name: t.Optional[str] = None) -> str:
747748
-------
748749
The msg_id of the message sent
749750
"""
750-
if target_name is None:
751-
content = {}
752-
else:
753-
content = {"target_name": target_name}
751+
content = {} if target_name is None else {"target_name": target_name}
754752
msg = self.session.msg("comm_info_request", content)
755753
self.shell_channel.send(msg)
756754
return msg["header"]["msg_id"]

jupyter_client/connect.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,8 @@ def find_connection_file(
218218

219219
matches = [os.path.abspath(m) for m in matches]
220220
if not matches:
221-
raise OSError(f"Could not find {filename!r} in {path!r}")
221+
msg = f"Could not find {filename!r} in {path!r}"
222+
raise OSError(msg)
222223
elif len(matches) == 1:
223224
return matches[0]
224225
else:
@@ -592,10 +593,11 @@ def _reconcile_connection_info(self, info: KernelConnectionInfo) -> None:
592593
# Ensure what is in KernelManager is what we expect.
593594
km_info = self.get_connection_info()
594595
if not self._equal_connections(info, km_info):
595-
raise ValueError(
596+
msg = (
596597
"KernelManager's connection information already exists and does not match "
597598
"the expected values returned from provisioner!"
598599
)
600+
raise ValueError(msg)
599601

600602
@staticmethod
601603
def _equal_connections(conn1: KernelConnectionInfo, conn2: KernelConnectionInfo) -> bool:
@@ -613,10 +615,7 @@ def _equal_connections(conn1: KernelConnectionInfo, conn2: KernelConnectionInfo)
613615
"signature_scheme",
614616
]
615617

616-
for key in pertinent_keys:
617-
if conn1.get(key) != conn2.get(key):
618-
return False
619-
return True
618+
return all(conn1.get(key) == conn2.get(key) for key in pertinent_keys)
620619

621620
# --------------------------------------------------------------------------
622621
# Creating connected sockets

jupyter_client/ioloop/manager.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,8 @@ def start_restarter(self):
6363

6464
def stop_restarter(self):
6565
"""Stop the restarter."""
66-
if self.autorestart:
67-
if self._restarter is not None:
68-
self._restarter.stop()
66+
if self.autorestart and self._restarter is not None:
67+
self._restarter.stop()
6968

7069
connect_shell = as_zmqstream(KernelManager.connect_shell)
7170
connect_control = as_zmqstream(KernelManager.connect_control)
@@ -107,9 +106,8 @@ def start_restarter(self):
107106

108107
def stop_restarter(self):
109108
"""Stop the restarter."""
110-
if self.autorestart:
111-
if self._restarter is not None:
112-
self._restarter.stop()
109+
if self.autorestart and self._restarter is not None:
110+
self._restarter.stop()
113111

114112
connect_shell = as_zmqstream(AsyncKernelManager.connect_shell)
115113
connect_control = as_zmqstream(AsyncKernelManager.connect_control)

jupyter_client/jsonutil.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929
# holy crap, strptime is not threadsafe.
3030
# Calling it once at import seems to help.
31-
datetime.strptime("1", "%d")
31+
datetime.strptime("1", "%d") # noqa
3232

3333
# -----------------------------------------------------------------------------
3434
# Classes and functions
@@ -174,10 +174,11 @@ def json_clean(obj):
174174
nkeys = len(obj)
175175
nkeys_collapsed = len(set(map(str, obj)))
176176
if nkeys != nkeys_collapsed:
177-
raise ValueError(
177+
msg = (
178178
'dict cannot be safely converted to JSON: '
179179
'key collision would lead to dropped values'
180180
)
181+
raise ValueError(msg)
181182
# If all OK, proceed by making the new dict that will be json-safe
182183
out = {}
183184
for k, v in obj.items():

jupyter_client/kernelspec.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -368,10 +368,12 @@ def install_kernel_spec(
368368
kernel_name = os.path.basename(source_dir)
369369
kernel_name = kernel_name.lower()
370370
if not _is_valid_kernel_name(kernel_name):
371-
raise ValueError(f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}")
371+
msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}"
372+
raise ValueError(msg)
372373

373374
if user and prefix:
374-
raise ValueError("Can't specify both user and prefix. Please choose one or the other.")
375+
msg = "Can't specify both user and prefix. Please choose one or the other."
376+
raise ValueError(msg)
375377

376378
if replace is not None:
377379
warnings.warn(

jupyter_client/launcher.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def launch_kernel(
6666
# stderr are all invalid.
6767
redirect_out = sys.executable.endswith("pythonw.exe")
6868
if redirect_out:
69-
blackhole = open(os.devnull, "w")
69+
blackhole = open(os.devnull, "w") # noqa
7070
_stdout = blackhole if stdout is None else stdout
7171
_stderr = blackhole if stderr is None else stderr
7272
else:
@@ -171,10 +171,9 @@ def launch_kernel(
171171
proc.win32_interrupt_event = interrupt_event
172172

173173
# Clean up pipes created to work around Popen bug.
174-
if redirect_in:
175-
if stdin is None:
176-
assert proc.stdin is not None
177-
proc.stdin.close()
174+
if redirect_in and stdin is None:
175+
assert proc.stdin is not None
176+
proc.stdin.close()
178177

179178
return proc
180179

jupyter_client/localinterfaces.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ def _get_output(cmd):
3939
p = Popen(cmd, stdout=PIPE, stderr=PIPE, startupinfo=startupinfo)
4040
stdout, stderr = p.communicate()
4141
if p.returncode:
42-
raise OSError("Failed to run {}: {}".format(cmd, stderr.decode("utf8", "replace")))
42+
msg = "Failed to run {}: {}".format(cmd, stderr.decode("utf8", "replace"))
43+
raise OSError(msg)
4344
return stdout.decode("utf8", "replace")
4445

4546

@@ -127,7 +128,7 @@ def _load_ips_ip():
127128
addrs = []
128129
for line in lines:
129130
blocks = line.lower().split()
130-
if (len(blocks) >= 2) and (blocks[0] == "inet"):
131+
if (len(blocks) >= 2) and (blocks[0] == "inet"): # noqa
131132
addrs.append(blocks[1].split("/")[0])
132133
_populate_from_list(addrs)
133134

jupyter_client/manager.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -541,7 +541,8 @@ async def _async_restart_kernel(
541541
kernel.
542542
"""
543543
if self._launch_args is None:
544-
raise RuntimeError("Cannot restart the kernel. No previous call to 'start_kernel'.")
544+
msg = "Cannot restart the kernel. No previous call to 'start_kernel'."
545+
raise RuntimeError(msg)
545546

546547
# Stop currently running kernel.
547548
await self._async_shutdown_kernel(now=now, restart=True)
@@ -597,17 +598,16 @@ async def _async_interrupt_kernel(self) -> None:
597598
Unlike ``signal_kernel``, this operation is well supported on all
598599
platforms.
599600
"""
600-
if not self.has_kernel:
601-
if self._ready is not None:
602-
if isinstance(self._ready, CFuture):
603-
ready = asyncio.ensure_future(t.cast(Future[t.Any], self._ready))
604-
else:
605-
ready = self._ready
606-
# Wait for a shutdown if one is in progress.
607-
if self.shutting_down:
608-
await ready
609-
# Wait for a startup.
601+
if not self.has_kernel and self._ready is not None:
602+
if isinstance(self._ready, CFuture):
603+
ready = asyncio.ensure_future(t.cast(Future[t.Any], self._ready))
604+
else:
605+
ready = self._ready
606+
# Wait for a shutdown if one is in progress.
607+
if self.shutting_down:
610608
await ready
609+
# Wait for a startup.
610+
await ready
611611

612612
if self.has_kernel:
613613
assert self.kernel_spec is not None
@@ -620,7 +620,8 @@ async def _async_interrupt_kernel(self) -> None:
620620
self._connect_control_socket()
621621
self.session.send(self._control_socket, msg)
622622
else:
623-
raise RuntimeError("Cannot interrupt kernel. No kernel is running!")
623+
msg = "Cannot interrupt kernel. No kernel is running!"
624+
raise RuntimeError(msg)
624625

625626
interrupt_kernel = run_sync(_async_interrupt_kernel)
626627

@@ -636,7 +637,8 @@ async def _async_signal_kernel(self, signum: int) -> None:
636637
assert self.provisioner is not None
637638
await self.provisioner.send_signal(signum)
638639
else:
639-
raise RuntimeError("Cannot signal kernel. No kernel is running!")
640+
msg = "Cannot signal kernel. No kernel is running!"
641+
raise RuntimeError(msg)
640642

641643
signal_kernel = run_sync(_async_signal_kernel)
642644

0 commit comments

Comments
 (0)