Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run Mypy by default. #1270

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .github/workflows/downstream.yml
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ jobs:

ipyparallel:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout
uses: actions/checkout@v4
Expand Down
21 changes: 18 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,33 @@ repos:
types_or: [yaml, html, json]

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.8.0"
rev: "v1.12.0"
hooks:
- id: mypy
files: ipykernel
stages: [manual]
args: ["--install-types", "--non-interactive"]
args: []
additional_dependencies:
[
"traitlets>=5.13",
"ipython>=8.16.1",
"jupyter_client>=8.5",
"appnope",
"types-Pygments",
"types-colorama",
"types-decorator",
"types-psutil",
"types-pycurl",
"types-python-dateutil",
"PyQt5",
"anyio",
"cloudpickle",
"comm",
"debugpy",
"dill",
"nest_asyncio",
"numpy",
"packaging",
"trio",
]

- repo: https://github.com/adamchainz/blacken-docs
Expand Down
16 changes: 8 additions & 8 deletions ipykernel/comm/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@

import comm.base_comm
import traitlets.config
from traitlets import Bool, Bytes, Instance, Unicode, default
from traitlets import Bool, Instance, Unicode, default

from ipykernel.jsonutil import json_clean
from ipykernel.kernelbase import Kernel


# this is the class that will be created if we do comm.create_comm
class BaseComm(comm.base_comm.BaseComm): # type:ignore[misc]
class BaseComm(comm.base_comm.BaseComm):
"""The base class for comms."""

kernel: Optional["Kernel"] = None
Expand Down Expand Up @@ -50,18 +50,18 @@ class Comm(BaseComm, traitlets.config.LoggingConfigurable):
"""Class for communicating between a Frontend and a Kernel"""

kernel = Instance("ipykernel.kernelbase.Kernel", allow_none=True) # type:ignore[assignment]
comm_id = Unicode()
primary = Bool(True, help="Am I the primary or secondary Comm?")
comm_id = Unicode() # type: ignore[assignment]
primary = Bool(True, help="Am I the primary or secondary Comm?") # type: ignore[assignment]

target_name = Unicode("comm")
target_module = Unicode(
target_name = Unicode("comm") # type: ignore[assignment]
target_module = Unicode( # type: ignore[assignment]
None,
allow_none=True,
help="""requirejs module from
which to load comm target.""",
)

topic = Bytes()
topic: bytes

@default("kernel")
def _default_kernel(self):
Expand Down Expand Up @@ -90,7 +90,7 @@ def __init__(
kernel = kwargs.pop("kernel", None)
if target_name:
kwargs["target_name"] = target_name
BaseComm.__init__(self, data=data, metadata=metadata, buffers=buffers, **kwargs) # type:ignore[call-arg]
BaseComm.__init__(self, data=data, metadata=metadata, buffers=buffers, **kwargs)
# only re-add kernel if explicitly provided
if had_kernel:
kwargs["kernel"] = kernel
Expand Down
9 changes: 5 additions & 4 deletions ipykernel/comm/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,19 @@
import comm.base_comm
import traitlets
import traitlets.config
from typing import Dict, Any

from .comm import Comm

logger = logging.getLogger("ipykernel.comm")


class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable): # type:ignore[misc]
class CommManager(comm.base_comm.CommManager, traitlets.config.LoggingConfigurable):
"""A comm manager."""

kernel = traitlets.Instance("ipykernel.kernelbase.Kernel")
comms = traitlets.Dict()
targets = traitlets.Dict()
comms: Dict[Any, Any]
targets: Dict[str, Any]

def __init__(self, **kwargs):
"""Initialize the manager."""
Expand All @@ -33,7 +34,7 @@ def comm_open(self, stream, ident, msg):
# but we should let the base class create the comm with comm.create_comm in a major release
content = msg["content"]
comm_id = content["comm_id"]
target_name = content["target_name"]
target_name: str = content["target_name"]
f = self.targets.get(target_name, None)
comm = Comm(
comm_id=comm_id,
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/datapub.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

try:
# available since ipyparallel 5.0.0
from ipyparallel.serialize import serialize_object
from ipyparallel.serialize import serialize_object # type: ignore[import-not-found]
except ImportError:
# Deprecated since ipykernel 4.3.0
from ipykernel.serialize import serialize_object
Expand Down
24 changes: 14 additions & 10 deletions ipykernel/debugger.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@

try:
# This import is required to have the next ones working...
from debugpy.server import api # noqa: F401
from debugpy.server import api # type: ignore[import-untyped]# noqa: F401

from _pydevd_bundle import pydevd_frame_utils # isort: skip
from _pydevd_bundle.pydevd_suspended_frames import ( # isort: skip
from _pydevd_bundle import ( # type:ignore[import-not-found]
pydevd_frame_utils,
) # isort: skip
from _pydevd_bundle.pydevd_suspended_frames import ( # type:ignore[import-not-found] # isort: skip
SuspendedFramesManager,
_FramesTracker,
)
Expand Down Expand Up @@ -70,7 +72,7 @@ class _DummyPyDB:

def __init__(self):
"""Init."""
from _pydevd_bundle.pydevd_api import PyDevdAPI
from _pydevd_bundle.pydevd_api import PyDevdAPI # type: ignore[import-not-found]

self.variable_presentation = PyDevdAPI.VariablePresentation()

Expand Down Expand Up @@ -117,9 +119,10 @@ def __init__(self, event_callback, log):
self.tcp_buffer = ""
self._reset_tcp_pos()
self.event_callback = event_callback
self.message_send_stream, self.message_receive_stream = create_memory_object_stream[dict](
max_buffer_size=inf
)
(
self.message_send_stream,
self.message_receive_stream,
) = create_memory_object_stream[dict[t.Any, t.Any]](max_buffer_size=inf)
self.log = log

def _reset_tcp_pos(self):
Expand Down Expand Up @@ -342,9 +345,10 @@ def __init__(
self.is_started = False
self.event_callback = event_callback
self.just_my_code = just_my_code
self.stopped_send_stream, self.stopped_receive_stream = create_memory_object_stream[dict](
max_buffer_size=inf
)
(
self.stopped_send_stream,
self.stopped_receive_stream,
) = create_memory_object_stream[dict[t.Any, t.Any]](max_buffer_size=inf)

self.started_debug_handlers = {}
for msg_type in Debugger.started_debug_msg_types:
Expand Down
10 changes: 5 additions & 5 deletions ipykernel/eventloops.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def _loop_wx(app):
def loop_wx(kernel):
"""Start a kernel with wx event loop support."""

import wx
import wx # type: ignore[import-not-found]

# Wx uses milliseconds
poll_interval = int(1000 * kernel._poll_interval)
Expand Down Expand Up @@ -279,7 +279,7 @@ def _schedule_exit(delay):
else:
import asyncio

import nest_asyncio
import nest_asyncio # type: ignore [import-untyped]

nest_asyncio.apply()

Expand Down Expand Up @@ -515,19 +515,19 @@ def set_qt_api_env_from_gui(gui):
os.environ["QT_API"] = "pyqt5"
except ImportError:
try:
import PySide2 # noqa: F401
import PySide2 # type: ignore[import-not-found] #noqa: F401

os.environ["QT_API"] = "pyside2"
except ImportError:
os.environ["QT_API"] = "pyqt5"
elif gui == "qt6":
try:
import PyQt6 # noqa: F401
import PyQt6 # type: ignore[import-not-found] #noqa: F401

os.environ["QT_API"] = "pyqt6"
except ImportError:
try:
import PySide6 # noqa: F401
import PySide6 # type: ignore[import-not-found] # noqa: F401

os.environ["QT_API"] = "pyside6"
except ImportError:
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/gui/gtk3embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@
import warnings

# Third-party
import gi
import gi # type: ignore[import-not-found]

gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import GObject, Gtk # noqa: E402
from gi.repository import GObject, Gtk # type: ignore[import-not-found] # noqa: E402

warnings.warn(
"The Gtk3 event loop for ipykernel is deprecated", category=DeprecationWarning, stacklevel=2
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/gui/gtkembed.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
import warnings

# Third-party
import gobject
import gtk
import gobject # type: ignore[import-not-found]
import gtk # type: ignore[import-not-found]

warnings.warn(
"The Gtk3 event loop for ipykernel is deprecated", category=DeprecationWarning, stacklevel=2
Expand Down
1 change: 1 addition & 0 deletions ipykernel/inprocess/blocking.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def call_handlers(self, msg):
_raw_input = self.client.kernel._sys_raw_input
prompt = msg["content"]["prompt"]
print(prompt, end="", file=sys.__stdout__)
assert sys.__stdout__ is not None
sys.__stdout__.flush()
self.client.input(_raw_input())

Expand Down
12 changes: 9 additions & 3 deletions ipykernel/inprocess/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _default_blocking_class(self):

return BlockingInProcessKernelClient

def get_connection_info(self):
def get_connection_info(self): # type:ignore [override]
"""Get the connection info for the client."""
d = super().get_connection_info()
d["kernel"] = self.kernel # type:ignore[assignment]
Expand Down Expand Up @@ -100,8 +100,14 @@ def hb_channel(self):
# Methods for sending specific messages
# -------------------------------------

async def execute(
self, code, silent=False, store_history=True, user_expressions=None, allow_stdin=None
async def execute( # type:ignore[override]
self,
code: str,
silent: bool = False,
store_history: bool = True,
user_expressions=None,
allow_stdin=None,
stop_on_error: bool = True,
):
"""Execute code on the client."""
if allow_stdin is None:
Expand Down
4 changes: 3 additions & 1 deletion ipykernel/inprocess/ipkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,9 @@ async def execute_request(self, stream, ident, parent):
with self._redirected_io():
await super().execute_request(stream, ident, parent)

async def start(self, *, task_status: TaskStatus = TASK_STATUS_IGNORED) -> None:
async def start(
self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED
) -> None:
"""Override registration of dispatchers for streams."""
if self.shell:
self.shell.exit_now = False
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/inprocess/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def _default_session(self):
# --------------------------------------------------------------------------

async def start_kernel( # type: ignore[explicit-override, override]
self, *, task_status: TaskStatus = TASK_STATUS_IGNORED, **kwds: Any
self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED, **kwds: Any
) -> None:
"""Start the kernel."""
from ipykernel.inprocess.ipkernel import InProcessKernel
Expand All @@ -65,7 +65,7 @@ async def restart_kernel( # type: ignore[explicit-override, override]
now: bool = False,
newports: bool = False,
*,
task_status: TaskStatus = TASK_STATUS_IGNORED,
task_status: TaskStatus[None] = TASK_STATUS_IGNORED,
**kw: Any,
) -> None:
"""Restart the kernel."""
Expand Down
2 changes: 1 addition & 1 deletion ipykernel/inprocess/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


class Session(_Session):
async def recv(self, socket, copy=True):
async def recv(self, socket, copy=True): # type:ignore[override]
return await socket.recv_multipart()

def send(
Expand Down
13 changes: 7 additions & 6 deletions ipykernel/inprocess/socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import zmq.asyncio
from anyio import create_memory_object_stream
from traitlets import HasTraits, Instance
from typing import Any

# -----------------------------------------------------------------------------
# Dummy socket class
Expand All @@ -32,12 +33,12 @@ def __init__(self, is_shell, *args, **kwargs):
self.is_shell = is_shell
self.on_recv = None
if is_shell:
self.in_send_stream, self.in_receive_stream = create_memory_object_stream[dict](
max_buffer_size=inf
)
self.out_send_stream, self.out_receive_stream = create_memory_object_stream[dict](
max_buffer_size=inf
)
self.in_send_stream, self.in_receive_stream = create_memory_object_stream[
dict[Any, Any]
](max_buffer_size=inf)
self.out_send_stream, self.out_receive_stream = create_memory_object_stream[
dict[Any, Any]
](max_buffer_size=inf)

def put(self, msg):
self.in_send_stream.send_nowait(msg)
Expand Down
6 changes: 4 additions & 2 deletions ipykernel/ipkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ async def poll_stopped_queue(self):
while True:
await self.debugger.handle_stopped_event()

async def start(self, *, task_status: TaskStatus = TASK_STATUS_IGNORED) -> None:
async def start(
self, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED
) -> None:
"""Start the kernel."""
if self.shell:
self.shell.exit_now = False
Expand Down Expand Up @@ -641,7 +643,7 @@ def do_is_complete(self, code):
def do_apply(self, content, bufs, msg_id, reply_metadata):
"""Handle an apply request."""
try:
from ipyparallel.serialize import serialize_object, unpack_apply_message
from ipyparallel.serialize import serialize_object, unpack_apply_message # type: ignore[import-not-found]
except ImportError:
from .serialize import serialize_object, unpack_apply_message

Expand Down
2 changes: 1 addition & 1 deletion ipykernel/kernelapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def _bind_socket(self, s, port):
raise
return None

def write_connection_file(self):
def write_connection_file(self): # type:ignore[override]
"""write connection info to JSON file"""
cf = self.abs_connection_file
connection_info = dict(
Expand Down
Loading
Loading