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
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ repos:
args: [--max-line-length=200]
stages: [manual]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.942
hooks:
- id: mypy
exclude: "ipykernel.*tests"
args: ["--config-file", "pyproject.toml"]
additional_dependencies: [tornado, jupyter_client, pytest]
stages: [manual]

- repo: https://github.com/pycqa/flake8
rev: 4.0.1
hooks:
Expand Down
1 change: 1 addition & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
include *.md
include pyproject.toml
include ipykernel/py.typed

# Documentation
graft docs
Expand Down
7 changes: 4 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

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

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
Expand Down Expand Up @@ -61,7 +62,7 @@
# built documents.
#

version_ns = {}
version_ns: Dict[str, Any] = {}
here = os.path.dirname(__file__)
version_py = os.path.join(here, os.pardir, "ipykernel", "_version.py")
with open(version_py) as f:
Expand Down Expand Up @@ -150,7 +151,7 @@
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
html_static_path: List[str] = []

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
Expand Down Expand Up @@ -217,7 +218,7 @@

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {}
latex_elements: Dict[str, object] = {}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
Expand Down
2 changes: 1 addition & 1 deletion examples/embedding/inprocess_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import tornado
from jupyter_console.ptshell import ZMQTerminalInteractiveShell

from ipykernel.inprocess import InProcessKernelManager
from ipykernel.inprocess.manager import InProcessKernelManager


def print_process_id():
Expand Down
6 changes: 4 additions & 2 deletions ipykernel/_eventloop_macos.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import ctypes.util
from threading import Event

objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc")) # type:ignore[arg-type]

void_p = ctypes.c_void_p

Expand Down Expand Up @@ -42,7 +42,9 @@ def C(classname):
# end obj-c boilerplate from appnope

# CoreFoundation C-API calls we will use:
CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library("CoreFoundation"))
CoreFoundation = ctypes.cdll.LoadLibrary(
ctypes.util.find_library("CoreFoundation") # type:ignore[arg-type]
)

CFAbsoluteTimeGetCurrent = CoreFoundation.CFAbsoluteTimeGetCurrent
CFAbsoluteTimeGetCurrent.restype = ctypes.c_double
Expand Down
4 changes: 3 additions & 1 deletion ipykernel/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
store the current version info of the server.
"""
import re
from typing import List

# Version string must appear intact for tbump versioning
__version__ = "6.12.1"

# Build up version_info tuple for backwards compatibility
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
match = re.match(pattern, __version__)
parts = [int(match[part]) for part in ["major", "minor", "patch"]]
assert match is not None
parts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]]
if match["rest"]:
parts.append(match["rest"])
version_info = tuple(parts)
Expand Down
11 changes: 7 additions & 4 deletions ipykernel/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import json
import sys
from subprocess import PIPE, Popen
from typing import Any, Dict

import jupyter_client
from jupyter_client import write_connection_file
Expand Down Expand Up @@ -68,13 +69,15 @@ def get_connection_info(connection_file=None, unpack=False):
cf = _find_connection_file(connection_file)

with open(cf) as f:
info = f.read()
info_str = f.read()

if unpack:
info = json.loads(info)
info = json.loads(info_str)
# ensure key is bytes:
info["key"] = info.get("key", "").encode()
return info
return info

return info_str


def connect_qtconsole(connection_file=None, argv=None):
Expand Down Expand Up @@ -105,7 +108,7 @@ def connect_qtconsole(connection_file=None, argv=None):

cmd = ";".join(["from IPython.qt.console import qtconsoleapp", "qtconsoleapp.main()"])

kwargs = {}
kwargs: Dict[str, Any] = {}
# Launch the Qt console in a separate session & process group, so
# interrupting the kernel doesn't kill it.
kwargs["start_new_session"] = True
Expand Down
13 changes: 7 additions & 6 deletions ipykernel/debugger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import os
import re
import sys
import typing as t

import zmq
from IPython.core.getipython import get_ipython
Expand Down Expand Up @@ -89,7 +90,7 @@ def __init__(self, event_callback, log):
self.tcp_buffer = ""
self._reset_tcp_pos()
self.event_callback = event_callback
self.message_queue = Queue()
self.message_queue: Queue[t.Any] = Queue()
self.log = log

def _reset_tcp_pos(self):
Expand All @@ -100,7 +101,7 @@ def _reset_tcp_pos(self):

def _put_message(self, raw_msg):
self.log.debug("QUEUE - _put_message:")
msg = jsonapi.loads(raw_msg)
msg = t.cast(t.Dict[str, t.Any], jsonapi.loads(raw_msg))
if msg["type"] == "event":
self.log.debug("QUEUE - received event:")
self.log.debug(msg)
Expand Down Expand Up @@ -290,7 +291,7 @@ def __init__(
self.is_started = False
self.event_callback = event_callback
self.just_my_code = just_my_code
self.stopped_queue = Queue()
self.stopped_queue: Queue[t.Any] = Queue()

self.started_debug_handlers = {}
for msg_type in Debugger.started_debug_msg_types:
Expand Down Expand Up @@ -357,9 +358,9 @@ async def handle_stopped_event(self):
event = await self.stopped_queue.get()
req = {"seq": event["seq"] + 1, "type": "request", "command": "threads"}
rep = await self._forward_message(req)
for t in rep["body"]["threads"]:
if self._accept_stopped_thread(t["name"]):
self.stopped_threads.add(t["id"])
for thread in rep["body"]["threads"]:
if self._accept_stopped_thread(thread["name"]):
self.stopped_threads.add(thread["id"])
self.event_callback(event)

@property
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/displayhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def __call__(self, obj):
if obj is None:
return

builtins._ = obj
builtins._ = obj # type:ignore[attr-defined]
sys.stdout.flush()
sys.stderr.flush()
contents = {
Expand Down
10 changes: 5 additions & 5 deletions ipykernel/eventloops.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def process_stream_events(stream, *a, **kw):

notifier = partial(process_stream_events, kernel.shell_stream)
# seems to be needed for tk
notifier.__name__ = "notifier"
notifier.__name__ = "notifier" # type:ignore[attr-defined]
app.tk.createfilehandler(kernel.shell_stream.getsockopt(zmq.FD), READABLE, notifier)
# schedule initial call after start
app.after(0, notifier)
Expand Down Expand Up @@ -386,7 +386,7 @@ def loop_asyncio(kernel):
# main loop is closed, create a new one
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop._should_close = False
loop._should_close = False # type:ignore[attr-defined]

# pause eventloop when there's an event on a zmq socket
def process_stream_events(stream):
Expand All @@ -406,7 +406,7 @@ def process_stream_events(stream):
continue
except Exception as e:
error = e
if loop._should_close:
if loop._should_close: # type:ignore[attr-defined]
loop.close()
if error is not None:
raise error
Expand All @@ -424,14 +424,14 @@ def loop_asyncio_exit(kernel):
def close_loop():
if hasattr(loop, "shutdown_asyncgens"):
yield from loop.shutdown_asyncgens()
loop._should_close = True
loop._should_close = True # type:ignore[attr-defined]
loop.stop()

if loop.is_running():
close_loop()

elif not loop.is_closed():
loop.run_until_complete(close_loop)
loop.run_until_complete(close_loop) # type:ignore[call-overload]
loop.close()


Expand Down
3 changes: 2 additions & 1 deletion ipykernel/gui/gtk3embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def stop(self):
# FIXME: this one isn't getting called because we have no reliable
# kernel shutdown. We need to fix that: once the kernel has a
# shutdown mechanism, it can call this.
self.gtk_main_quit()
if self.gtk_main_quit:
self.gtk_main_quit()
sys.exit()

def _hijack_gtk(self):
Expand Down
3 changes: 2 additions & 1 deletion ipykernel/gui/gtkembed.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ def stop(self):
# FIXME: this one isn't getting called because we have no reliable
# kernel shutdown. We need to fix that: once the kernel has a
# shutdown mechanism, it can call this.
self.gtk_main_quit()
if self.gtk_main_quit:
self.gtk_main_quit()
sys.exit()

def _hijack_gtk(self):
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/heartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _try_bind_socket(self):

def _bind_socket(self):
try:
win_in_use = errno.WSAEADDRINUSE
win_in_use = errno.WSAEADDRINUSE # type:ignore[attr-defined]
except AttributeError:
win_in_use = None

Expand Down
2 changes: 1 addition & 1 deletion ipykernel/inprocess/blocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
class BlockingInProcessChannel(InProcessChannel):
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self._in_queue = Queue()
self._in_queue: Queue[object] = Queue()

def call_handlers(self, msg):
self._in_queue.put(msg)
Expand Down
4 changes: 3 additions & 1 deletion ipykernel/inprocess/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

from typing import List

from jupyter_client.channelsabc import HBChannelABC

# -----------------------------------------------------------------------------
Expand All @@ -13,7 +15,7 @@
class InProcessChannel:
"""Base class for in-process channels."""

proxy_methods = []
proxy_methods: List[object] = []

def __init__(self, client=None):
super().__init__()
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/inprocess/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def recv_multipart(self, flags=0, copy=True, track=False):
return self.queue.get_nowait()

def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
msg_parts = list(map(zmq.Message, msg_parts))
msg_parts = list(map(zmq.Message, msg_parts)) # type:ignore[arg-type]
self.queue.put_nowait(msg_parts)
self.message_sent += 1

Expand Down
Loading