Skip to content

Commit ca30c80

Browse files
committed
Add basic mypy support
1 parent 1baecb8 commit ca30c80

31 files changed

+142
-77
lines changed

.pre-commit-config.yaml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,15 @@ repos:
4141
args: [--max-line-length=200]
4242
stages: [manual]
4343

44+
- repo: https://github.com/pre-commit/mirrors-mypy
45+
rev: v0.942
46+
hooks:
47+
- id: mypy
48+
exclude: 'ipykernel.*tests'
49+
args: ["--config-file", "pyproject.toml"]
50+
additional_dependencies: [tornado, jupyter_client, pytest]
51+
stages: [manual]
52+
4453
- repo: https://github.com/pycqa/flake8
4554
rev: 4.0.1
4655
hooks:

MANIFEST.in

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
include *.md
22
include pyproject.toml
3+
include ipykernel/py.typed
34

45
# Documentation
56
graft docs

docs/conf.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
# built documents.
6262
#
6363

64-
version_ns = {}
64+
version_ns: dict = {}
6565
here = os.path.dirname(__file__)
6666
version_py = os.path.join(here, os.pardir, "ipykernel", "_version.py")
6767
with open(version_py) as f:
@@ -150,7 +150,7 @@
150150
# Add any paths that contain custom static files (such as style sheets) here,
151151
# relative to this directory. They are copied after the builtin static files,
152152
# so a file named "default.css" will overwrite the builtin "default.css".
153-
html_static_path = []
153+
html_static_path: list = []
154154

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

218218
# -- Options for LaTeX output ---------------------------------------------
219219

220-
latex_elements = {}
220+
latex_elements: dict = {}
221221

222222
# Grouping the document tree into LaTeX files. List of tuples
223223
# (source start file, target name, title,

ipykernel/_eventloop_macos.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import ctypes.util
1111
from threading import Event
1212

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

1515
void_p = ctypes.c_void_p
1616

@@ -42,7 +42,7 @@ def C(classname):
4242
# end obj-c boilerplate from appnope
4343

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

4747
CFAbsoluteTimeGetCurrent = CoreFoundation.CFAbsoluteTimeGetCurrent
4848
CFAbsoluteTimeGetCurrent.restype = ctypes.c_double

ipykernel/_version.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
# Build up version_info tuple for backwards compatibility
1010
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
1111
match = re.match(pattern, __version__)
12-
parts = [int(match[part]) for part in ["major", "minor", "patch"]]
12+
assert match is not None
13+
parts: list = [int(match[part]) for part in ["major", "minor", "patch"]]
1314
if match["rest"]:
1415
parts.append(match["rest"])
1516
version_info = tuple(parts)

ipykernel/connect.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import json
77
import sys
88
from subprocess import PIPE, Popen
9+
from typing import Any
910

1011
import jupyter_client
1112
from jupyter_client import write_connection_file
@@ -68,13 +69,15 @@ def get_connection_info(connection_file=None, unpack=False):
6869
cf = _find_connection_file(connection_file)
6970

7071
with open(cf) as f:
71-
info = f.read()
72+
info_str = f.read()
7273

7374
if unpack:
74-
info = json.loads(info)
75+
info = json.loads(info_str)
7576
# ensure key is bytes:
7677
info["key"] = info.get("key", "").encode()
77-
return info
78+
return info
79+
80+
return info_str
7881

7982

8083
def connect_qtconsole(connection_file=None, argv=None):
@@ -105,7 +108,7 @@ def connect_qtconsole(connection_file=None, argv=None):
105108

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

108-
kwargs = {}
111+
kwargs: dict[str, Any] = {}
109112
# Launch the Qt console in a separate session & process group, so
110113
# interrupting the kernel doesn't kill it.
111114
kwargs["start_new_session"] = True

ipykernel/debugger.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import os
22
import re
33
import sys
4+
import typing as t
45

56
import zmq
67
from IPython.core.getipython import get_ipython
@@ -89,7 +90,7 @@ def __init__(self, event_callback, log):
8990
self.tcp_buffer = ""
9091
self._reset_tcp_pos()
9192
self.event_callback = event_callback
92-
self.message_queue = Queue()
93+
self.message_queue: Queue = Queue()
9394
self.log = log
9495

9596
def _reset_tcp_pos(self):
@@ -100,7 +101,7 @@ def _reset_tcp_pos(self):
100101

101102
def _put_message(self, raw_msg):
102103
self.log.debug("QUEUE - _put_message:")
103-
msg = jsonapi.loads(raw_msg)
104+
msg = t.cast(dict, jsonapi.loads(raw_msg))
104105
if msg["type"] == "event":
105106
self.log.debug("QUEUE - received event:")
106107
self.log.debug(msg)
@@ -290,7 +291,7 @@ def __init__(
290291
self.is_started = False
291292
self.event_callback = event_callback
292293
self.just_my_code = just_my_code
293-
self.stopped_queue = Queue()
294+
self.stopped_queue: Queue = Queue()
294295

295296
self.started_debug_handlers = {}
296297
for msg_type in Debugger.started_debug_msg_types:

ipykernel/displayhook.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __call__(self, obj):
3232
if obj is None:
3333
return
3434

35-
builtins._ = obj
35+
builtins._ = obj # type:ignore[attr-defined]
3636
sys.stdout.flush()
3737
sys.stderr.flush()
3838
contents = {

ipykernel/eventloops.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def process_stream_events(stream, *a, **kw):
248248

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

391391
# pause eventloop when there's an event on a zmq socket
392392
def process_stream_events(stream):
@@ -406,7 +406,7 @@ def process_stream_events(stream):
406406
continue
407407
except Exception as e:
408408
error = e
409-
if loop._should_close:
409+
if loop._should_close: # type:ignore[attr-defined]
410410
loop.close()
411411
if error is not None:
412412
raise error
@@ -424,14 +424,14 @@ def loop_asyncio_exit(kernel):
424424
def close_loop():
425425
if hasattr(loop, "shutdown_asyncgens"):
426426
yield from loop.shutdown_asyncgens()
427-
loop._should_close = True
427+
loop._should_close = True # type:ignore[attr-defined]
428428
loop.stop()
429429

430430
if loop.is_running():
431431
close_loop()
432432

433433
elif not loop.is_closed():
434-
loop.run_until_complete(close_loop)
434+
loop.run_until_complete(close_loop) # type:ignore[call-overload]
435435
loop.close()
436436

437437

ipykernel/gui/gtk3embed.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414
import sys
1515

1616
# Third-party
17-
import gi
17+
import gi # type:ignore[import]
1818

1919
gi.require_version("Gdk", "3.0")
2020
gi.require_version("Gtk", "3.0")
21-
from gi.repository import GObject, Gtk
21+
from gi.repository import GObject, Gtk # type:ignore[import]
2222

2323
# -----------------------------------------------------------------------------
2424
# Classes and functions
@@ -63,7 +63,8 @@ def stop(self):
6363
# FIXME: this one isn't getting called because we have no reliable
6464
# kernel shutdown. We need to fix that: once the kernel has a
6565
# shutdown mechanism, it can call this.
66-
self.gtk_main_quit()
66+
if self.gtk_main_quit:
67+
self.gtk_main_quit()
6768
sys.exit()
6869

6970
def _hijack_gtk(self):

0 commit comments

Comments
 (0)