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

Improve mypy config #769

Merged
merged 3 commits into from
Apr 13, 2022
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
3 changes: 0 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,6 @@ jobs:
pip install -e .[test]
pip freeze

- name: Check types
run: mypy jupyter_client --exclude '\/tests|kernelspecapp|ioloop|runapp' --install-types --non-interactive

- name: Run the tests
if: ${{ !startsWith(matrix.python-version, 'pypy') && !startsWith(matrix.os, 'windows') }}
run: |
Expand Down
9 changes: 9 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ repos:
"flake8-implicit-str-concat==0.2.0",
]

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

- repo: https://github.com/PyCQA/doc8
rev: 0.11.1
hooks:
Expand Down
6 changes: 3 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
# |version| and |release|, also used in various other places throughout the
# built documents.
#
version_ns = {}
version_ns: dict = {}
here = os.path.dirname(__file__)
version_py = os.path.join(here, os.pardir, 'jupyter_client', '_version.py')
with open(version_py) as f:
Expand Down Expand Up @@ -219,7 +219,7 @@

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

latex_elements = {
latex_elements: dict = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
Expand Down Expand Up @@ -312,7 +312,7 @@
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
import sphinx_rtd_theme # type:ignore[import]

html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
Expand Down
2 changes: 1 addition & 1 deletion jupyter_client/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def handle_reply_status_error(self, msg: Dict[str, Any]) -> Dict[str, Any]:
"""
return msg

def __call__(self, msg: Dict[str, Any]):
def __call__(self, msg: Dict[str, Any]) -> Dict[str, Any]:
msg = self.update_header(msg)
msg = self.update_metadata(msg)
msg = self.update_msg_type(msg)
Expand Down
2 changes: 1 addition & 1 deletion jupyter_client/asynchronous/client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Implements an async kernel client"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from traitlets import Type # type: ignore
from traitlets import Type

from jupyter_client.channels import HBChannel
from jupyter_client.channels import ZMQSocketChannel
Expand Down
2 changes: 1 addition & 1 deletion jupyter_client/blocking/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from traitlets import Type # type: ignore
from traitlets import Type

from ..utils import run_sync
from jupyter_client.channels import HBChannel
Expand Down
4 changes: 2 additions & 2 deletions jupyter_client/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class HBChannel(Thread):

def __init__(
self,
context: zmq.asyncio.Context = None,
context: t.Optional[zmq.asyncio.Context] = None,
session: t.Optional[Session] = None,
address: t.Union[t.Tuple[str, int], str] = "",
):
Expand Down Expand Up @@ -210,7 +210,7 @@ def __init__(
self.socket: t.Optional[zmq.sugar.socket.Socket] = socket
self.session = session

async def _recv(self, **kwargs) -> t.Dict[str, t.Any]:
async def _recv(self, **kwargs: t.Any) -> t.Dict[str, t.Any]:
assert self.socket is not None
msg = await self.socket.recv_multipart(**kwargs)
ident, smsg = self.session.feed_identities(msg)
Expand Down
14 changes: 7 additions & 7 deletions jupyter_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from queue import Empty

import zmq.asyncio
from traitlets import Any # type: ignore
from traitlets import Any
from traitlets import Bool
from traitlets import Instance
from traitlets import Type
Expand Down Expand Up @@ -120,19 +120,19 @@ def _context_default(self) -> zmq.asyncio.Context:
# Channel proxy methods
# --------------------------------------------------------------------------

async def _async_get_shell_msg(self, *args, **kwargs) -> t.Dict[str, t.Any]:
async def _async_get_shell_msg(self, *args: Any, **kwargs: Any) -> t.Dict[str, t.Any]:
"""Get a message from the shell channel"""
return await self.shell_channel.get_msg(*args, **kwargs)

async def _async_get_iopub_msg(self, *args, **kwargs) -> t.Dict[str, t.Any]:
async def _async_get_iopub_msg(self, *args: Any, **kwargs: Any) -> t.Dict[str, t.Any]:
"""Get a message from the iopub channel"""
return await self.iopub_channel.get_msg(*args, **kwargs)

async def _async_get_stdin_msg(self, *args, **kwargs) -> t.Dict[str, t.Any]:
async def _async_get_stdin_msg(self, *args: Any, **kwargs: Any) -> t.Dict[str, t.Any]:
"""Get a message from the stdin channel"""
return await self.stdin_channel.get_msg(*args, **kwargs)

async def _async_get_control_msg(self, *args, **kwargs) -> t.Dict[str, t.Any]:
async def _async_get_control_msg(self, *args: Any, **kwargs: Any) -> t.Dict[str, t.Any]:
"""Get a message from the control channel"""
return await self.control_channel.get_msg(*args, **kwargs)

Expand Down Expand Up @@ -253,7 +253,7 @@ def _output_hook_kernel(
self,
session: Session,
socket: zmq.sugar.socket.Socket,
parent_header,
parent_header: Any,
msg: t.Dict[str, t.Any],
) -> None:
"""Output hook when running inside an IPython kernel
Expand Down Expand Up @@ -676,7 +676,7 @@ def history(
raw: bool = True,
output: bool = False,
hist_access_type: str = "range",
**kwargs,
**kwargs: Any,
) -> str:
"""Get entries from the kernel's history list.

Expand Down
10 changes: 5 additions & 5 deletions jupyter_client/connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@
from typing import Tuple
from typing import Union

import zmq # type: ignore
from jupyter_core.paths import jupyter_data_dir # type: ignore
import zmq
from jupyter_core.paths import jupyter_data_dir
from jupyter_core.paths import jupyter_runtime_dir
from jupyter_core.paths import secure_write
from traitlets import Bool # type: ignore
from traitlets import Bool
from traitlets import CaselessStrEnum
from traitlets import Instance
from traitlets import Int
from traitlets import Integer
from traitlets import observe
from traitlets import Type
from traitlets import Unicode
from traitlets.config import LoggingConfigurable # type: ignore
from traitlets.config import LoggingConfigurable
from traitlets.config import SingletonConfigurable

from .localinterfaces import localhost
Expand Down Expand Up @@ -644,7 +644,7 @@ class is attempting to resolve (minimize).
See: https://github.com/jupyter/jupyter_client/issues/487
"""

def __init__(self, **kwargs) -> None:
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.currently_used_ports: Set[int] = set()

Expand Down
10 changes: 5 additions & 5 deletions jupyter_client/consoleapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@
import warnings
from typing import cast

from jupyter_core.application import base_aliases # type: ignore
from jupyter_core.application import base_aliases
from jupyter_core.application import base_flags
from traitlets import CBool # type: ignore
from traitlets import CBool
from traitlets import CUnicode
from traitlets import Dict
from traitlets import List
from traitlets import Type
from traitlets import Unicode
from traitlets.config.application import boolean_flag # type: ignore
from traitlets.config.application import boolean_flag

from . import connect
from . import find_connection_file
Expand Down Expand Up @@ -155,7 +155,7 @@ def _connection_file_default(self) -> str:
to force a direct exit without any confirmation.""",
)

def build_kernel_argv(self, argv=None) -> None:
def build_kernel_argv(self, argv: object = None) -> None:
"""build argv to be passed to kernel subprocess

Override in subclasses if any args should be passed to the kernel
Expand Down Expand Up @@ -354,7 +354,7 @@ def init_kernel_client(self) -> None:

self.kernel_client.start_channels()

def initialize(self, argv=None) -> None:
def initialize(self, argv: object = None) -> None:
"""
Classes which mix this class in should call:
JupyterConsoleApp.initialize(self,argv)
Expand Down
4 changes: 2 additions & 2 deletions jupyter_client/kernelapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import signal
import uuid

from jupyter_core.application import base_flags # type: ignore
from jupyter_core.application import base_flags
from jupyter_core.application import JupyterApp
from tornado.ioloop import IOLoop
from traitlets import Unicode # type: ignore
from traitlets import Unicode

from . import __version__
from .kernelspec import KernelSpecManager
Expand Down
8 changes: 4 additions & 4 deletions jupyter_client/kernelspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@
import shutil
import warnings

from jupyter_core.paths import jupyter_data_dir # type: ignore
from jupyter_core.paths import jupyter_data_dir
from jupyter_core.paths import jupyter_path
from jupyter_core.paths import SYSTEM_JUPYTER_PATH
from traitlets import Bool # type: ignore
from traitlets import Bool
from traitlets import CaselessStrEnum
from traitlets import Dict
from traitlets import HasTraits
Expand All @@ -20,7 +20,7 @@
from traitlets import Set
from traitlets import Type
from traitlets import Unicode
from traitlets.config import LoggingConfigurable # type: ignore
from traitlets.config import LoggingConfigurable

from .provisioning import KernelProvisionerFactory as KPF

Expand Down Expand Up @@ -175,7 +175,7 @@ def _user_kernel_dir_default(self):
def _deprecated_trait(self, change):
"""observer for deprecated traits"""
old_attr = change.name
new_attr, version = self._deprecated_aliases.get(old_attr)
new_attr, version = self._deprecated_aliases[old_attr]
new_value = getattr(self, new_attr)
if new_value != change.new:
# only warn if different
Expand Down
5 changes: 3 additions & 2 deletions jupyter_client/kernelspecapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import os.path
import sys
import typing as t

from jupyter_core.application import base_aliases
from jupyter_core.application import base_flags
Expand Down Expand Up @@ -309,8 +310,8 @@ class KernelSpecApp(Application):
}
)

aliases = {}
flags = {}
aliases: t.Dict[str, object] = {}
flags: t.Dict[str, object] = {}

def start(self):
if self.subapp is None:
Expand Down
9 changes: 5 additions & 4 deletions jupyter_client/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
import sys
from subprocess import PIPE
from subprocess import Popen
from typing import Any
from typing import Dict
from typing import List
from typing import Optional

from traitlets.log import get_logger # type: ignore
from traitlets.log import get_logger


def launch_kernel(
Expand All @@ -20,7 +21,7 @@ def launch_kernel(
env: Optional[Dict[str, str]] = None,
independent: bool = False,
cwd: Optional[str] = None,
**kw,
**kw: Any,
) -> Popen:
"""Launches a localhost kernel, binding to the specified ports.

Expand Down Expand Up @@ -108,7 +109,7 @@ def launch_kernel(
GetCurrentProcess,
)
except: # noqa
from _subprocess import ( # type: ignore
from _subprocess import (
GetCurrentProcess,
CREATE_NEW_PROCESS_GROUP,
DUPLICATE_SAME_ACCESS,
Expand Down Expand Up @@ -170,7 +171,7 @@ def launch_kernel(

if sys.platform == "win32":
# Attach the interrupt event to the Popen objet so it can be used later.
proc.win32_interrupt_event = interrupt_event # type: ignore
proc.win32_interrupt_event = interrupt_event

# Clean up pipes created to work around Popen bug.
if redirect_in:
Expand Down
14 changes: 10 additions & 4 deletions jupyter_client/localinterfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import subprocess
from subprocess import PIPE
from subprocess import Popen
from typing import Iterable
from typing import List
from warnings import warn

Expand All @@ -16,22 +17,27 @@
LOCALHOST = ""


def _uniq_stable(elems):
def _uniq_stable(elems: Iterable) -> List:
"""uniq_stable(elems) -> list

Return from an iterable, a list of all the unique elements in the input,
maintaining the order in which they first appear.
"""
seen = set()
return [x for x in elems if x not in seen and not seen.add(x)]
value = []
for x in elems:
if x not in seen:
value.append(x)
seen.add(x)
return value


def _get_output(cmd):
"""Get output of a command, raising IOError if it fails"""
startupinfo = None
if os.name == "nt":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo = subprocess.STARTUPINFO() # type:ignore[attr-defined]
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type:ignore[attr-defined]
p = Popen(cmd, stdout=PIPE, stderr=PIPE, startupinfo=startupinfo)
stdout, stderr = p.communicate()
if p.returncode:
Expand Down
Loading