Skip to content

Commit

Permalink
Update ruff and typings (#1167)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 committed Nov 21, 2023
1 parent 5b72bfe commit 465d344
Show file tree
Hide file tree
Showing 42 changed files with 234 additions and 273 deletions.
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Expand Up @@ -34,13 +34,13 @@ repos:
[mdformat-gfm, mdformat-frontmatter, mdformat-footnote]

- repo: https://github.com/pre-commit/mirrors-prettier
rev: "v3.0.3"
rev: "v3.1.0"
hooks:
- id: prettier
types_or: [yaml, html, json]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.6.1"
rev: "v1.7.0"
hooks:
- id: mypy
files: ipykernel
Expand Down Expand Up @@ -74,7 +74,7 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.5
rev: v0.1.6
hooks:
- id: ruff
types_or: [python, jupyter]
Expand All @@ -83,7 +83,7 @@ repos:
types_or: [python, jupyter]

- repo: https://github.com/scientific-python/cookie
rev: "2023.10.27"
rev: "2023.11.17"
hooks:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"]
14 changes: 6 additions & 8 deletions docs/conf.py
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
#
# IPython Kernel documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 5 11:32:44 2015.
#
Expand All @@ -14,6 +12,7 @@

import os
import shutil
from pathlib import Path
from typing import Any, Dict, List

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

try:
import enchant # noqa
import enchant

extensions += ["sphinxcontrib.spelling"]
except ImportError:
Expand Down Expand Up @@ -72,10 +71,10 @@
#

version_ns: Dict[str, Any] = {}
here = os.path.dirname(__file__)
version_py = os.path.join(here, os.pardir, "ipykernel", "_version.py")
here = Path(__file__).parent.resolve()
version_py = Path(here) / os.pardir / "ipykernel" / "_version.py"
with open(version_py) as f:
exec(compile(f.read(), version_py, "exec"), version_ns) # noqa
exec(compile(f.read(), version_py, "exec"), version_ns)

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


def setup(app):
here = os.path.dirname(os.path.abspath(__file__))
shutil.copy(os.path.join(here, "..", "CHANGELOG.md"), "changelog.md")
shutil.copy(Path(here) / ".." / "CHANGELOG.md", "changelog.md")
9 changes: 5 additions & 4 deletions hatch_build.py
Expand Up @@ -2,6 +2,7 @@
import os
import shutil
import sys
from pathlib import Path

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

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

def initialize(self, version, build_data):
"""Initialize the hook."""
here = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, here)
here = Path(__file__).parent.resolve()
sys.path.insert(0, str(here))
from ipykernel.kernelspec import make_ipkernel_cmd, write_kernel_spec

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

overrides["argv"] = argv

dest = os.path.join(here, "data_kernelspec")
if os.path.exists(dest):
dest = Path(here) / "data_kernelspec"
if Path(dest).exists():
shutil.rmtree(dest)

write_kernel_spec(dest, overrides=overrides)
12 changes: 7 additions & 5 deletions ipykernel/__init__.py
@@ -1,5 +1,7 @@
from ._version import __version__ # noqa
from ._version import kernel_protocol_version # noqa
from ._version import kernel_protocol_version_info # noqa
from ._version import version_info # noqa
from .connect import * # noqa
from ._version import (
__version__,
kernel_protocol_version,
kernel_protocol_version_info,
version_info,
)
from .connect import *
2 changes: 1 addition & 1 deletion ipykernel/_eventloop_macos.py
Expand Up @@ -75,7 +75,7 @@ def C(classname):
CFRunLoopAddTimer.restype = None
CFRunLoopAddTimer.argtypes = [void_p, void_p, void_p]

kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, "kCFRunLoopCommonModes") # noqa
kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, "kCFRunLoopCommonModes")


def _NSApp():
Expand Down
1 change: 1 addition & 0 deletions ipykernel/comm/comm.py
Expand Up @@ -67,6 +67,7 @@ class Comm(BaseComm, traitlets.config.LoggingConfigurable):
def _default_kernel(self):
if Kernel.initialized():
return Kernel.instance()
return None

@default("comm_id")
def _default_comm_id(self):
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/comm/manager.py
Expand Up @@ -49,13 +49,13 @@ def comm_open(self, stream, ident, msg):
f(comm, msg)
return
except Exception:
logger.error("Exception opening comm with target: %s", target_name, exc_info=True)
logger.error("Exception opening comm with target: %s", target_name, exc_info=True) # noqa: G201

# Failure.
try:
comm.close()
except Exception:
logger.error(
logger.error( # noqa: G201
"""Could not close comm during `comm_open` failure
clean-up. The comm may not have been opened yet.""",
exc_info=True,
Expand Down
5 changes: 2 additions & 3 deletions ipykernel/compiler.py
Expand Up @@ -45,7 +45,7 @@ def murmur2_x86(data, seed):
return h


convert_to_long_pathname = lambda filename: filename # noqa
convert_to_long_pathname = lambda filename: filename

if sys.platform == "win32":
try:
Expand Down Expand Up @@ -80,8 +80,7 @@ def get_tmp_directory():

def get_tmp_hash_seed():
"""Get a temp hash seed."""
hash_seed = 0xC70F6907
return hash_seed
return 0xC70F6907


def get_file_name(code):
Expand Down
5 changes: 2 additions & 3 deletions ipykernel/connect.py
Expand Up @@ -46,8 +46,7 @@ def _find_connection_file(connection_file):
if connection_file is None:
# get connection file from current kernel
return get_connection_file()
else:
return jupyter_client.find_connection_file(connection_file)
return jupyter_client.find_connection_file(connection_file)


def get_connection_info(
Expand Down Expand Up @@ -125,7 +124,7 @@ def connect_qtconsole(
kwargs["start_new_session"] = True

return Popen(
[sys.executable, "-c", cmd, "--existing", cf, *argv], # noqa: S603
[sys.executable, "-c", cmd, "--existing", cf, *argv],
stdout=PIPE,
stderr=PIPE,
close_fds=(sys.platform != "win32"),
Expand Down
66 changes: 30 additions & 36 deletions ipykernel/debugger.py
Expand Up @@ -3,6 +3,7 @@
import re
import sys
import typing as t
from pathlib import Path

import zmq
from IPython.core.getipython import get_ipython
Expand All @@ -20,7 +21,7 @@

try:
# This import is required to have the next ones working...
from debugpy.server import api # noqa
from debugpy.server import api

from _pydevd_bundle import pydevd_frame_utils # isort: skip
from _pydevd_bundle.pydevd_suspended_frames import ( # isort: skip
Expand Down Expand Up @@ -179,10 +180,10 @@ def put_tcp_frame(self, frame):
self.tcp_buffer = ""
self._reset_tcp_pos()
return
else:
self.tcp_buffer = self.tcp_buffer[self.message_pos + self.message_size :]
self.log.debug("QUEUE - slicing tcp_buffer: %s", self.tcp_buffer)
self._reset_tcp_pos()

self.tcp_buffer = self.tcp_buffer[self.message_pos + self.message_size :]
self.log.debug("QUEUE - slicing tcp_buffer: %s", self.tcp_buffer)
self._reset_tcp_pos()

async def get_message(self):
"""Get a message from the queue."""
Expand Down Expand Up @@ -256,8 +257,7 @@ async def _handle_init_sequence(self):
await self._wait_for_response()

# 4] Waits for attachResponse and returns it
attach_rep = await self._wait_for_response()
return attach_rep
return await self._wait_for_response()

def get_host_port(self):
"""Get the host debugpy port."""
Expand Down Expand Up @@ -294,11 +294,11 @@ async def send_dap_request(self, msg):
rep = await self._handle_init_sequence()
self.wait_for_attach = False
return rep
else:
rep = await self._wait_for_response()
self.log.debug("DEBUGPYCLIENT - returning:")
self.log.debug(rep)
return rep

rep = await self._wait_for_response()
self.log.debug("DEBUGPYCLIENT - returning:")
self.log.debug(rep)
return rep


class Debugger:
Expand Down Expand Up @@ -363,9 +363,8 @@ def _handle_event(self, msg):
self.stopped_queue.put_nowait(msg)
# Do not forward the event now, will be done in the handle_stopped_event
return
else:
self.stopped_threads.add(msg["body"]["threadId"])
self.event_callback(msg)
self.stopped_threads.add(msg["body"]["threadId"])
self.event_callback(msg)
elif msg["event"] == "continued":
if msg["body"]["allThreadsContinued"]:
self.stopped_threads = set()
Expand All @@ -380,15 +379,14 @@ async def _forward_message(self, msg):

def _build_variables_response(self, request, variables):
var_list = [var for var in variables if self.accept_variable(var["name"])]
reply = {
return {
"seq": request["seq"],
"type": "response",
"request_seq": request["seq"],
"success": True,
"command": request["command"],
"body": {"variables": var_list},
}
return reply

def _accept_stopped_thread(self, thread_name):
# TODO: identify Thread-2, Thread-3 and Thread-4. These are NOT
Expand Down Expand Up @@ -416,8 +414,8 @@ def start(self):
"""Start the debugger."""
if not self.debugpy_initialized:
tmp_dir = get_tmp_directory()
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
if not Path(tmp_dir).exists():
Path(tmp_dir).mkdir(parents=True)
host, port = self.debugpy_client.get_host_port()
code = "import debugpy;"
code += 'debugpy.listen(("' + host + '",' + port + "))"
Expand Down Expand Up @@ -460,14 +458,13 @@ async def dumpCell(self, message):
with open(file_name, "w", encoding="utf-8") as f:
f.write(code)

reply = {
return {
"type": "response",
"request_seq": message["seq"],
"success": True,
"command": message["command"],
"body": {"sourcePath": file_name},
}
return reply

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

async def variables(self, message):
"""Handle a variables message."""
Expand All @@ -557,12 +554,12 @@ async def variables(self, message):
message["arguments"]["variablesReference"]
)
return self._build_variables_response(message, variables)
else:
reply = await self._forward_message(message)
# TODO : check start and count arguments work as expected in debugpy
reply["body"]["variables"] = [
var for var in reply["body"]["variables"] if self.accept_variable(var["name"])
]

reply = await self._forward_message(message)
# TODO : check start and count arguments work as expected in debugpy
reply["body"]["variables"] = [
var for var in reply["body"]["variables"] if self.accept_variable(var["name"])
]
return reply

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

async def configurationDone(self, message):
"""Handle a configuration done message."""
reply = {
return {
"seq": message["seq"],
"type": "response",
"request_seq": message["seq"],
"success": True,
"command": message["command"],
}
return reply

async def debugInfo(self, message):
"""Handle a debug info message."""
breakpoint_list = []
for key, value in self.breakpoint_list.items():
breakpoint_list.append({"source": key, "breakpoints": value})
reply = {
return {
"type": "response",
"request_seq": message["seq"],
"success": True,
Expand All @@ -611,7 +607,6 @@ async def debugInfo(self, message):
"exceptionPaths": ["Python Exceptions"],
},
}
return reply

async def inspectVariables(self, message):
"""Handle an insepct variables message."""
Expand Down Expand Up @@ -665,7 +660,7 @@ async def richInspectVariables(self, message):
}
)
if reply["success"]:
repr_data, repr_metadata = eval(reply["body"]["result"], {}, {}) # noqa: S307
repr_data, repr_metadata = eval(reply["body"]["result"], {}, {}) # noqa: PGH001

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

reply = {"body": {"modules": mods, "totalModules": len(modules)}}
return reply
return {"body": {"modules": mods, "totalModules": len(modules)}}

async def process_request(self, message):
"""Process a request."""
Expand Down

0 comments on commit 465d344

Please sign in to comment.