Skip to content

Commit 51a613d

Browse files
authored
Merge pull request #913 from blink1073/add-mypy
Add basic mypy support
2 parents 1baecb8 + 71b9265 commit 51a613d

30 files changed

+130
-71
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: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import os
1616
import shutil
17+
from typing import Any, Dict, List
1718

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

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

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

218219
# -- Options for LaTeX output ---------------------------------------------
219220

220-
latex_elements = {}
221+
latex_elements: Dict[str, object] = {}
221222

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

examples/embedding/inprocess_terminal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import tornado
55
from jupyter_console.ptshell import ZMQTerminalInteractiveShell
66

7-
from ipykernel.inprocess import InProcessKernelManager
7+
from ipykernel.inprocess.manager import InProcessKernelManager
88

99

1010
def print_process_id():

ipykernel/_eventloop_macos.py

Lines changed: 4 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,9 @@ 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(
46+
ctypes.util.find_library("CoreFoundation") # type:ignore[arg-type]
47+
)
4648

4749
CFAbsoluteTimeGetCurrent = CoreFoundation.CFAbsoluteTimeGetCurrent
4850
CFAbsoluteTimeGetCurrent.restype = ctypes.c_double

ipykernel/_version.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,16 @@
22
store the current version info of the server.
33
"""
44
import re
5+
from typing import List
56

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

910
# Build up version_info tuple for backwards compatibility
1011
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
1112
match = re.match(pattern, __version__)
12-
parts = [int(match[part]) for part in ["major", "minor", "patch"]]
13+
assert match is not None
14+
parts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]]
1315
if match["rest"]:
1416
parts.append(match["rest"])
1517
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, Dict
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: 7 additions & 6 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[t.Any] = 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(t.Dict[str, t.Any], 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[t.Any] = Queue()
294295

295296
self.started_debug_handlers = {}
296297
for msg_type in Debugger.started_debug_msg_types:
@@ -357,9 +358,9 @@ async def handle_stopped_event(self):
357358
event = await self.stopped_queue.get()
358359
req = {"seq": event["seq"] + 1, "type": "request", "command": "threads"}
359360
rep = await self._forward_message(req)
360-
for t in rep["body"]["threads"]:
361-
if self._accept_stopped_thread(t["name"]):
362-
self.stopped_threads.add(t["id"])
361+
for thread in rep["body"]["threads"]:
362+
if self._accept_stopped_thread(thread["name"]):
363+
self.stopped_threads.add(thread["id"])
363364
self.event_callback(event)
364365

365366
@property

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

0 commit comments

Comments
 (0)