Skip to content

Commit 465d344

Browse files
authored
Update ruff and typings (#1167)
1 parent 5b72bfe commit 465d344

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+234
-273
lines changed

.pre-commit-config.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,13 @@ repos:
3434
[mdformat-gfm, mdformat-frontmatter, mdformat-footnote]
3535

3636
- repo: https://github.com/pre-commit/mirrors-prettier
37-
rev: "v3.0.3"
37+
rev: "v3.1.0"
3838
hooks:
3939
- id: prettier
4040
types_or: [yaml, html, json]
4141

4242
- repo: https://github.com/pre-commit/mirrors-mypy
43-
rev: "v1.6.1"
43+
rev: "v1.7.0"
4444
hooks:
4545
- id: mypy
4646
files: ipykernel
@@ -74,7 +74,7 @@ repos:
7474
- id: rst-inline-touching-normal
7575

7676
- repo: https://github.com/astral-sh/ruff-pre-commit
77-
rev: v0.1.5
77+
rev: v0.1.6
7878
hooks:
7979
- id: ruff
8080
types_or: [python, jupyter]
@@ -83,7 +83,7 @@ repos:
8383
types_or: [python, jupyter]
8484

8585
- repo: https://github.com/scientific-python/cookie
86-
rev: "2023.10.27"
86+
rev: "2023.11.17"
8787
hooks:
8888
- id: sp-repo-review
8989
additional_dependencies: ["repo-review[cli]"]

docs/conf.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
#!/usr/bin/env python3
2-
#
31
# IPython Kernel documentation build configuration file, created by
42
# sphinx-quickstart on Mon Oct 5 11:32:44 2015.
53
#
@@ -14,6 +12,7 @@
1412

1513
import os
1614
import shutil
15+
from pathlib import Path
1716
from typing import Any, Dict, List
1817

1918
# If extensions (or modules to document with autodoc) are in another directory,
@@ -38,7 +37,7 @@
3837
]
3938

4039
try:
41-
import enchant # noqa
40+
import enchant
4241

4342
extensions += ["sphinxcontrib.spelling"]
4443
except ImportError:
@@ -72,10 +71,10 @@
7271
#
7372

7473
version_ns: Dict[str, Any] = {}
75-
here = os.path.dirname(__file__)
76-
version_py = os.path.join(here, os.pardir, "ipykernel", "_version.py")
74+
here = Path(__file__).parent.resolve()
75+
version_py = Path(here) / os.pardir / "ipykernel" / "_version.py"
7776
with open(version_py) as f:
78-
exec(compile(f.read(), version_py, "exec"), version_ns) # noqa
77+
exec(compile(f.read(), version_py, "exec"), version_ns)
7978

8079
# The short X.Y version.
8180
version = "%i.%i" % version_ns["version_info"][:2]
@@ -312,5 +311,4 @@
312311

313312

314313
def setup(app):
315-
here = os.path.dirname(os.path.abspath(__file__))
316-
shutil.copy(os.path.join(here, "..", "CHANGELOG.md"), "changelog.md")
314+
shutil.copy(Path(here) / ".." / "CHANGELOG.md", "changelog.md")

hatch_build.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import os
33
import shutil
44
import sys
5+
from pathlib import Path
56

67
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
78

@@ -11,8 +12,8 @@ class CustomHook(BuildHookInterface):
1112

1213
def initialize(self, version, build_data):
1314
"""Initialize the hook."""
14-
here = os.path.abspath(os.path.dirname(__file__))
15-
sys.path.insert(0, here)
15+
here = Path(__file__).parent.resolve()
16+
sys.path.insert(0, str(here))
1617
from ipykernel.kernelspec import make_ipkernel_cmd, write_kernel_spec
1718

1819
overrides = {}
@@ -28,8 +29,8 @@ def initialize(self, version, build_data):
2829

2930
overrides["argv"] = argv
3031

31-
dest = os.path.join(here, "data_kernelspec")
32-
if os.path.exists(dest):
32+
dest = Path(here) / "data_kernelspec"
33+
if Path(dest).exists():
3334
shutil.rmtree(dest)
3435

3536
write_kernel_spec(dest, overrides=overrides)

ipykernel/__init__.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
from ._version import __version__ # noqa
2-
from ._version import kernel_protocol_version # noqa
3-
from ._version import kernel_protocol_version_info # noqa
4-
from ._version import version_info # noqa
5-
from .connect import * # noqa
1+
from ._version import (
2+
__version__,
3+
kernel_protocol_version,
4+
kernel_protocol_version_info,
5+
version_info,
6+
)
7+
from .connect import *

ipykernel/_eventloop_macos.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def C(classname):
7575
CFRunLoopAddTimer.restype = None
7676
CFRunLoopAddTimer.argtypes = [void_p, void_p, void_p]
7777

78-
kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, "kCFRunLoopCommonModes") # noqa
78+
kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, "kCFRunLoopCommonModes")
7979

8080

8181
def _NSApp():

ipykernel/comm/comm.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ class Comm(BaseComm, traitlets.config.LoggingConfigurable):
6767
def _default_kernel(self):
6868
if Kernel.initialized():
6969
return Kernel.instance()
70+
return None
7071

7172
@default("comm_id")
7273
def _default_comm_id(self):

ipykernel/comm/manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,13 @@ def comm_open(self, stream, ident, msg):
4949
f(comm, msg)
5050
return
5151
except Exception:
52-
logger.error("Exception opening comm with target: %s", target_name, exc_info=True)
52+
logger.error("Exception opening comm with target: %s", target_name, exc_info=True) # noqa: G201
5353

5454
# Failure.
5555
try:
5656
comm.close()
5757
except Exception:
58-
logger.error(
58+
logger.error( # noqa: G201
5959
"""Could not close comm during `comm_open` failure
6060
clean-up. The comm may not have been opened yet.""",
6161
exc_info=True,

ipykernel/compiler.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def murmur2_x86(data, seed):
4545
return h
4646

4747

48-
convert_to_long_pathname = lambda filename: filename # noqa
48+
convert_to_long_pathname = lambda filename: filename
4949

5050
if sys.platform == "win32":
5151
try:
@@ -80,8 +80,7 @@ def get_tmp_directory():
8080

8181
def get_tmp_hash_seed():
8282
"""Get a temp hash seed."""
83-
hash_seed = 0xC70F6907
84-
return hash_seed
83+
return 0xC70F6907
8584

8685

8786
def get_file_name(code):

ipykernel/connect.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,7 @@ def _find_connection_file(connection_file):
4646
if connection_file is None:
4747
# get connection file from current kernel
4848
return get_connection_file()
49-
else:
50-
return jupyter_client.find_connection_file(connection_file)
49+
return jupyter_client.find_connection_file(connection_file)
5150

5251

5352
def get_connection_info(
@@ -125,7 +124,7 @@ def connect_qtconsole(
125124
kwargs["start_new_session"] = True
126125

127126
return Popen(
128-
[sys.executable, "-c", cmd, "--existing", cf, *argv], # noqa: S603
127+
[sys.executable, "-c", cmd, "--existing", cf, *argv],
129128
stdout=PIPE,
130129
stderr=PIPE,
131130
close_fds=(sys.platform != "win32"),

ipykernel/debugger.py

Lines changed: 30 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44
import sys
55
import typing as t
6+
from pathlib import Path
67

78
import zmq
89
from IPython.core.getipython import get_ipython
@@ -20,7 +21,7 @@
2021

2122
try:
2223
# This import is required to have the next ones working...
23-
from debugpy.server import api # noqa
24+
from debugpy.server import api
2425

2526
from _pydevd_bundle import pydevd_frame_utils # isort: skip
2627
from _pydevd_bundle.pydevd_suspended_frames import ( # isort: skip
@@ -179,10 +180,10 @@ def put_tcp_frame(self, frame):
179180
self.tcp_buffer = ""
180181
self._reset_tcp_pos()
181182
return
182-
else:
183-
self.tcp_buffer = self.tcp_buffer[self.message_pos + self.message_size :]
184-
self.log.debug("QUEUE - slicing tcp_buffer: %s", self.tcp_buffer)
185-
self._reset_tcp_pos()
183+
184+
self.tcp_buffer = self.tcp_buffer[self.message_pos + self.message_size :]
185+
self.log.debug("QUEUE - slicing tcp_buffer: %s", self.tcp_buffer)
186+
self._reset_tcp_pos()
186187

187188
async def get_message(self):
188189
"""Get a message from the queue."""
@@ -256,8 +257,7 @@ async def _handle_init_sequence(self):
256257
await self._wait_for_response()
257258

258259
# 4] Waits for attachResponse and returns it
259-
attach_rep = await self._wait_for_response()
260-
return attach_rep
260+
return await self._wait_for_response()
261261

262262
def get_host_port(self):
263263
"""Get the host debugpy port."""
@@ -294,11 +294,11 @@ async def send_dap_request(self, msg):
294294
rep = await self._handle_init_sequence()
295295
self.wait_for_attach = False
296296
return rep
297-
else:
298-
rep = await self._wait_for_response()
299-
self.log.debug("DEBUGPYCLIENT - returning:")
300-
self.log.debug(rep)
301-
return rep
297+
298+
rep = await self._wait_for_response()
299+
self.log.debug("DEBUGPYCLIENT - returning:")
300+
self.log.debug(rep)
301+
return rep
302302

303303

304304
class Debugger:
@@ -363,9 +363,8 @@ def _handle_event(self, msg):
363363
self.stopped_queue.put_nowait(msg)
364364
# Do not forward the event now, will be done in the handle_stopped_event
365365
return
366-
else:
367-
self.stopped_threads.add(msg["body"]["threadId"])
368-
self.event_callback(msg)
366+
self.stopped_threads.add(msg["body"]["threadId"])
367+
self.event_callback(msg)
369368
elif msg["event"] == "continued":
370369
if msg["body"]["allThreadsContinued"]:
371370
self.stopped_threads = set()
@@ -380,15 +379,14 @@ async def _forward_message(self, msg):
380379

381380
def _build_variables_response(self, request, variables):
382381
var_list = [var for var in variables if self.accept_variable(var["name"])]
383-
reply = {
382+
return {
384383
"seq": request["seq"],
385384
"type": "response",
386385
"request_seq": request["seq"],
387386
"success": True,
388387
"command": request["command"],
389388
"body": {"variables": var_list},
390389
}
391-
return reply
392390

393391
def _accept_stopped_thread(self, thread_name):
394392
# TODO: identify Thread-2, Thread-3 and Thread-4. These are NOT
@@ -416,8 +414,8 @@ def start(self):
416414
"""Start the debugger."""
417415
if not self.debugpy_initialized:
418416
tmp_dir = get_tmp_directory()
419-
if not os.path.exists(tmp_dir):
420-
os.makedirs(tmp_dir)
417+
if not Path(tmp_dir).exists():
418+
Path(tmp_dir).mkdir(parents=True)
421419
host, port = self.debugpy_client.get_host_port()
422420
code = "import debugpy;"
423421
code += 'debugpy.listen(("' + host + '",' + port + "))"
@@ -460,14 +458,13 @@ async def dumpCell(self, message):
460458
with open(file_name, "w", encoding="utf-8") as f:
461459
f.write(code)
462460

463-
reply = {
461+
return {
464462
"type": "response",
465463
"request_seq": message["seq"],
466464
"success": True,
467465
"command": message["command"],
468466
"body": {"sourcePath": file_name},
469467
}
470-
return reply
471468

472469
async def setBreakpoints(self, message):
473470
"""Handle a set breakpoints message."""
@@ -487,7 +484,7 @@ async def source(self, message):
487484
"""Handle a source message."""
488485
reply = {"type": "response", "request_seq": message["seq"], "command": message["command"]}
489486
source_path = message["arguments"]["source"]["path"]
490-
if os.path.isfile(source_path):
487+
if Path(source_path).is_file():
491488
with open(source_path, encoding="utf-8") as f:
492489
reply["success"] = True
493490
reply["body"] = {"content": f.read()}
@@ -547,7 +544,7 @@ def accept_variable(self, variable_name):
547544
cond = variable_name not in forbid_list
548545
cond = cond and not bool(re.search(r"^_\d", variable_name))
549546
cond = cond and variable_name[0:2] != "_i"
550-
return cond
547+
return cond # noqa: RET504
551548

552549
async def variables(self, message):
553550
"""Handle a variables message."""
@@ -557,12 +554,12 @@ async def variables(self, message):
557554
message["arguments"]["variablesReference"]
558555
)
559556
return self._build_variables_response(message, variables)
560-
else:
561-
reply = await self._forward_message(message)
562-
# TODO : check start and count arguments work as expected in debugpy
563-
reply["body"]["variables"] = [
564-
var for var in reply["body"]["variables"] if self.accept_variable(var["name"])
565-
]
557+
558+
reply = await self._forward_message(message)
559+
# TODO : check start and count arguments work as expected in debugpy
560+
reply["body"]["variables"] = [
561+
var for var in reply["body"]["variables"] if self.accept_variable(var["name"])
562+
]
566563
return reply
567564

568565
async def attach(self, message):
@@ -580,21 +577,20 @@ async def attach(self, message):
580577

581578
async def configurationDone(self, message):
582579
"""Handle a configuration done message."""
583-
reply = {
580+
return {
584581
"seq": message["seq"],
585582
"type": "response",
586583
"request_seq": message["seq"],
587584
"success": True,
588585
"command": message["command"],
589586
}
590-
return reply
591587

592588
async def debugInfo(self, message):
593589
"""Handle a debug info message."""
594590
breakpoint_list = []
595591
for key, value in self.breakpoint_list.items():
596592
breakpoint_list.append({"source": key, "breakpoints": value})
597-
reply = {
593+
return {
598594
"type": "response",
599595
"request_seq": message["seq"],
600596
"success": True,
@@ -611,7 +607,6 @@ async def debugInfo(self, message):
611607
"exceptionPaths": ["Python Exceptions"],
612608
},
613609
}
614-
return reply
615610

616611
async def inspectVariables(self, message):
617612
"""Handle an insepct variables message."""
@@ -665,7 +660,7 @@ async def richInspectVariables(self, message):
665660
}
666661
)
667662
if reply["success"]:
668-
repr_data, repr_metadata = eval(reply["body"]["result"], {}, {}) # noqa: S307
663+
repr_data, repr_metadata = eval(reply["body"]["result"], {}, {}) # noqa: PGH001
669664

670665
body = {
671666
"data": repr_data,
@@ -708,8 +703,7 @@ async def modules(self, message):
708703
if filename and filename.endswith(".py"):
709704
mods.append({"id": i, "name": module.__name__, "path": filename})
710705

711-
reply = {"body": {"modules": mods, "totalModules": len(modules)}}
712-
return reply
706+
return {"body": {"modules": mods, "totalModules": len(modules)}}
713707

714708
async def process_request(self, message):
715709
"""Process a request."""

0 commit comments

Comments
 (0)