diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index fbc07722b..c7c8562af 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -34,16 +34,16 @@ repos: hooks: - id: prettier - # - repo: https://github.com/pycqa/flake8 - # rev: 4.0.1 - # hooks: - # - id: flake8 - # additional_dependencies: - # [ - # "flake8-bugbear==20.1.4", - # "flake8-logging-format==0.6.0", - # "flake8-implicit-str-concat==0.2.0", - # ] + - repo: https://github.com/pycqa/flake8 + rev: 4.0.1 + hooks: + - id: flake8 + additional_dependencies: + [ + "flake8-bugbear==20.1.4", + "flake8-logging-format==0.6.0", + "flake8-implicit-str-concat==0.2.0", + ] - repo: https://github.com/pre-commit/mirrors-eslint rev: v8.12.0 diff --git a/docs/conf.py b/docs/conf.py index e331f558a..a1ad70d12 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -217,16 +217,7 @@ # -- Options for LaTeX output --------------------------------------------- -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - #'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - #'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - #'preamble': '', - # Latex figure (float) alignment - #'figure_align': 'htbp', -} +latex_elements = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, diff --git a/examples/embedding/internal_ipkernel.py b/examples/embedding/internal_ipkernel.py index 9538aacc9..46e97a5e6 100644 --- a/examples/embedding/internal_ipkernel.py +++ b/examples/embedding/internal_ipkernel.py @@ -19,7 +19,7 @@ def mpl_kernel(gui): [ "python", "--matplotlib=%s" % gui, - #'--log-level=10' + #'--log-level=10' # noqa ] ) return kernel diff --git a/ipykernel/__init__.py b/ipykernel/__init__.py index bc5fbb726..a6c1666d6 100644 --- a/ipykernel/__init__.py +++ b/ipykernel/__init__.py @@ -1,7 +1,5 @@ -from ._version import ( - __version__, - kernel_protocol_version, - kernel_protocol_version_info, - version_info, -) -from .connect import * +from ._version import __version__ # noqa +from ._version import kernel_protocol_version # noqa +from ._version import kernel_protocol_version_info # noqa +from ._version import version_info # noqa +from .connect import * # noqa diff --git a/ipykernel/comm/__init__.py b/ipykernel/comm/__init__.py index cf9c1e983..f82cf5448 100644 --- a/ipykernel/comm/__init__.py +++ b/ipykernel/comm/__init__.py @@ -1,2 +1,2 @@ -from .comm import * -from .manager import * +from .comm import * # noqa +from .manager import * # noqa diff --git a/ipykernel/compiler.py b/ipykernel/compiler.py index 585261593..387e49b3e 100644 --- a/ipykernel/compiler.py +++ b/ipykernel/compiler.py @@ -43,7 +43,7 @@ def murmur2_x86(data, seed): return h -convert_to_long_pathname = lambda filename: filename +convert_to_long_pathname = lambda filename: filename # noqa if sys.platform == "win32": try: @@ -63,7 +63,7 @@ def _convert_to_long_pathname(filename): # test that it works so if there are any issues we fail just once here _convert_to_long_pathname(__file__) - except: + except Exception: pass else: convert_to_long_pathname = _convert_to_long_pathname diff --git a/ipykernel/debugger.py b/ipykernel/debugger.py index 62082a3cd..8368acccc 100644 --- a/ipykernel/debugger.py +++ b/ipykernel/debugger.py @@ -1,7 +1,6 @@ import os import re import sys -import threading import zmq from IPython.core.getipython import get_ipython diff --git a/ipykernel/eventloops.py b/ipykernel/eventloops.py index eae3a9e59..23f5f632b 100644 --- a/ipykernel/eventloops.py +++ b/ipykernel/eventloops.py @@ -128,12 +128,12 @@ def loop_qt5(kernel): """Start a kernel with PyQt5 event loop integration.""" if os.environ.get("QT_API", None) is None: try: - import PyQt5 + import PyQt5 # noqa os.environ["QT_API"] = "pyqt5" except ImportError: try: - import PySide2 + import PySide2 # noqa os.environ["QT_API"] = "pyside2" except ImportError: diff --git a/ipykernel/inprocess/__init__.py b/ipykernel/inprocess/__init__.py index b10698910..5d5147172 100644 --- a/ipykernel/inprocess/__init__.py +++ b/ipykernel/inprocess/__init__.py @@ -1,4 +1,4 @@ -from .blocking import BlockingInProcessKernelClient -from .channels import InProcessChannel, InProcessHBChannel -from .client import InProcessKernelClient -from .manager import InProcessKernelManager +from .blocking import BlockingInProcessKernelClient # noqa +from .channels import InProcessChannel, InProcessHBChannel # noqa +from .client import InProcessKernelClient # noqa +from .manager import InProcessKernelManager # noqa diff --git a/ipykernel/inprocess/client.py b/ipykernel/inprocess/client.py index b8d57085f..807cad760 100644 --- a/ipykernel/inprocess/client.py +++ b/ipykernel/inprocess/client.py @@ -99,7 +99,7 @@ def hb_channel(self): # ------------------------------------- def execute( - self, code, silent=False, store_history=True, user_expressions={}, allow_stdin=None + self, code, silent=False, store_history=True, user_expressions=None, allow_stdin=None ): if allow_stdin is None: allow_stdin = self.allow_stdin @@ -107,7 +107,7 @@ def execute( code=code, silent=silent, store_history=store_history, - user_expressions=user_expressions, + user_expressions=user_expressions or {}, allow_stdin=allow_stdin, ) msg = self.session.msg("execute_request", content) diff --git a/ipykernel/inprocess/tests/test_kernel.py b/ipykernel/inprocess/tests/test_kernel.py index 28b176f80..83d1924b5 100644 --- a/ipykernel/inprocess/tests/test_kernel.py +++ b/ipykernel/inprocess/tests/test_kernel.py @@ -64,7 +64,7 @@ def setUp(self): def test_pylab(self): """Does %pylab work in the in-process kernel?""" - matplotlib = pytest.importorskip("matplotlib", reason="This test requires matplotlib") + _ = pytest.importorskip("matplotlib", reason="This test requires matplotlib") kc = self.kc kc.execute("%pylab") out, err = assemble_output(kc.get_iopub_msg) diff --git a/ipykernel/iostream.py b/ipykernel/iostream.py index fa038359b..782ac5ad9 100644 --- a/ipykernel/iostream.py +++ b/ipykernel/iostream.py @@ -12,7 +12,6 @@ import warnings from binascii import b2a_hex from collections import deque -from imp import lock_held as import_lock_held from io import StringIO, TextIOBase from weakref import WeakSet @@ -122,7 +121,7 @@ def _handle_event(self, msg): # freeze event count so new writes don't extend the queue # while we are processing n_events = len(self._events) - for i in range(n_events): + for _ in range(n_events): event_f = self._events.popleft() event_f() @@ -475,16 +474,13 @@ def flush(self): # request flush on the background thread self.pub_thread.schedule(self._flush) # wait for flush to actually get through, if we can. - # waiting across threads during import can cause deadlocks - # so only wait if import lock is not held - if not import_lock_held(): - evt = threading.Event() - self.pub_thread.schedule(evt.set) - # and give a timeout to avoid - if not evt.wait(self.flush_timeout): - # write directly to __stderr__ instead of warning because - # if this is happening sys.stderr may be the problem. - print("IOStream.flush timed out", file=sys.__stderr__) + evt = threading.Event() + self.pub_thread.schedule(evt.set) + # and give a timeout to avoid + if not evt.wait(self.flush_timeout): + # write directly to __stderr__ instead of warning because + # if this is happening sys.stderr may be the problem. + print("IOStream.flush timed out", file=sys.__stderr__) else: self._flush() diff --git a/ipykernel/ipkernel.py b/ipykernel/ipkernel.py index 350f7f9fd..1757b8503 100644 --- a/ipykernel/ipkernel.py +++ b/ipykernel/ipkernel.py @@ -307,9 +307,10 @@ async def do_execute( run_cell = shell.run_cell_async should_run_async = shell.should_run_async else: - should_run_async = lambda cell: False + should_run_async = lambda cell: False # noqa # older IPython, # use blocking run_cell and wrap it in coroutine + async def run_cell(*args, **kwargs): return shell.run_cell(*args, **kwargs) diff --git a/ipykernel/kernelbase.py b/ipykernel/kernelbase.py index 12a3d93b0..5ef16fb37 100644 --- a/ipykernel/kernelbase.py +++ b/ipykernel/kernelbase.py @@ -942,7 +942,7 @@ async def usage_request(self, stream, ident, parent): cpu_percent = psutil.cpu_percent() # https://psutil.readthedocs.io/en/latest/index.html?highlight=cpu#psutil.cpu_percent # The first time cpu_percent is called it will return a meaningless 0.0 value which you are supposed to ignore. - if cpu_percent != None and cpu_percent != 0.0: + if cpu_percent is not None and cpu_percent != 0.0: reply_content["host_cpu_percent"] = cpu_percent reply_content["host_virtual_memory"] = dict(psutil.virtual_memory()._asdict()) reply_msg = self.session.send(stream, "usage_reply", reply_content, parent, ident) @@ -1083,7 +1083,7 @@ def _no_raw_input(self): """Raise StdinNotImplementedError if active frontend doesn't support stdin.""" raise StdinNotImplementedError( - "raw_input was called, but this " "frontend does not support stdin." + "raw_input was called, but this frontend does not support stdin." ) def getpass(self, prompt="", stream=None): diff --git a/ipykernel/pickleutil.py b/ipykernel/pickleutil.py index 82c588311..9ebd904d7 100644 --- a/ipykernel/pickleutil.py +++ b/ipykernel/pickleutil.py @@ -118,7 +118,7 @@ def use_cloudpickle(): class CannedObject: - def __init__(self, obj, keys=[], hook=None): + def __init__(self, obj, keys=None, hook=None): """can an object for safe pickling Parameters @@ -136,7 +136,7 @@ def __init__(self, obj, keys=[], hook=None): large data may be offloaded into the buffers list, used for zero-copy transfers. """ - self.keys = keys + self.keys = keys or [] self.obj = copy.copy(obj) self.hook = can(hook) for key in keys: @@ -326,7 +326,7 @@ def _import_mapping(mapping, original=None): """import any string-keys in a type mapping""" log = get_logger() log.debug("Importing canning map") - for key, value in list(mapping.items()): + for key, _ in list(mapping.items()): if isinstance(key, str): try: cls = import_item(key) diff --git a/ipykernel/pylab/config.py b/ipykernel/pylab/config.py index 09e2bef6a..7622f9e11 100644 --- a/ipykernel/pylab/config.py +++ b/ipykernel/pylab/config.py @@ -8,6 +8,6 @@ from matplotlib_inline.config import * # analysis: ignore # noqa F401 warnings.warn( - "`ipykernel.pylab.config` is deprecated, directly " "use `matplotlib_inline.config`", + "`ipykernel.pylab.config` is deprecated, directly use `matplotlib_inline.config`", DeprecationWarning, ) diff --git a/ipykernel/serialize.py b/ipykernel/serialize.py index 43247d3ff..6a1b79f78 100644 --- a/ipykernel/serialize.py +++ b/ipykernel/serialize.py @@ -189,7 +189,7 @@ def unpack_apply_message(bufs, g=None, copy=True): arg_bufs, kwarg_bufs = bufs[: info["narg_bufs"]], bufs[info["narg_bufs"] :] args = [] - for i in range(info["nargs"]): + for _ in range(info["nargs"]): arg, arg_bufs = deserialize_object(arg_bufs, g) args.append(arg) args = tuple(args) diff --git a/ipykernel/tests/__init__.py b/ipykernel/tests/__init__.py index 6ca7492a0..d2606e108 100644 --- a/ipykernel/tests/__init__.py +++ b/ipykernel/tests/__init__.py @@ -7,9 +7,6 @@ import tempfile from unittest.mock import patch -from IPython import paths as ipaths -from jupyter_core import paths as jpaths - from ipykernel.kernelspec import install pjoin = os.path.join diff --git a/ipykernel/tests/test_async.py b/ipykernel/tests/test_async.py index b36fedff0..81a8e3d95 100644 --- a/ipykernel/tests/test_async.py +++ b/ipykernel/tests/test_async.py @@ -1,9 +1,5 @@ """Test async/await integration""" -import sys -from distutils.version import LooseVersion as V - -import IPython import pytest from .test_message_spec import validate_message diff --git a/ipykernel/tests/test_connect.py b/ipykernel/tests/test_connect.py index 8e584ce20..4bb998ae1 100644 --- a/ipykernel/tests/test_connect.py +++ b/ipykernel/tests/test_connect.py @@ -35,7 +35,7 @@ class DummyKernelApp(IPKernelApp): def _default_shell_port(self): return 0 - def initialize(self, argv=[]): + def initialize(self, argv=None): self.init_profile_dir() self.init_connection_file() diff --git a/ipykernel/tests/test_embed_kernel.py b/ipykernel/tests/test_embed_kernel.py index 89c02565f..81eb234de 100644 --- a/ipykernel/tests/test_embed_kernel.py +++ b/ipykernel/tests/test_embed_kernel.py @@ -164,7 +164,7 @@ def test_embed_kernel_reentrant(): " embed_kernel()", " count = count + 1", "", - "while True:" " go()", + "while True: go()", "", ] ) diff --git a/ipykernel/tests/test_eventloop.py b/ipykernel/tests/test_eventloop.py index c0db7ff66..35818515e 100644 --- a/ipykernel/tests/test_eventloop.py +++ b/ipykernel/tests/test_eventloop.py @@ -1,7 +1,5 @@ """Test eventloop integration""" -import sys - import pytest import tornado diff --git a/ipykernel/tests/test_kernel.py b/ipykernel/tests/test_kernel.py index 7118f0a4f..40b9471eb 100644 --- a/ipykernel/tests/test_kernel.py +++ b/ipykernel/tests/test_kernel.py @@ -336,7 +336,7 @@ def test_message_order(): cell = "a += 1\na" msg_ids = [] # submit N executions as fast as we can - for i in range(N): + for _ in range(N): msg_ids.append(kc.execute(cell)) # check message-handling order for i, msg_id in enumerate(msg_ids, offset): @@ -388,7 +388,7 @@ def test_shutdown(): execute("a = 1", kc=kc) wait_for_idle(kc) kc.shutdown() - for i in range(300): # 30s timeout + for _ in range(300): # 30s timeout if km.is_alive(): time.sleep(0.1) else: @@ -482,7 +482,7 @@ def test_control_thread_priority(): # now send N control messages control_msg_ids = [] - for i in range(N): + for _ in range(N): msg = kc.session.msg("kernel_info_request", {}) kc.control_channel.send(msg) control_msg_ids.append(msg["header"]["msg_id"]) @@ -557,7 +557,7 @@ def test_shutdown_subprocesses(): wait_for_idle(kc) kc.shutdown() - for i in range(300): # 30s timeout + for _ in range(300): # 30s timeout if km.is_alive(): time.sleep(0.1) else: diff --git a/ipykernel/tests/test_message_spec.py b/ipykernel/tests/test_message_spec.py index 1a9cc58c1..94cf107f5 100644 --- a/ipykernel/tests/test_message_spec.py +++ b/ipykernel/tests/test_message_spec.py @@ -528,7 +528,7 @@ def test_single_payload(): """ flush_channels() msg_id, reply = execute( - code="ip = get_ipython()\n" "for i in range(3):\n" " ip.set_next_input('Hello There')\n" + code="ip = get_ipython()\nfor i in range(3):\n ip.set_next_input('Hello There')\n" ) payload = reply["payload"] next_input_pls = [pl for pl in payload if pl["source"] == "set_next_input"] diff --git a/ipykernel/tests/utils.py b/ipykernel/tests/utils.py index 711c45542..8ca55b1e7 100644 --- a/ipykernel/tests/utils.py +++ b/ipykernel/tests/utils.py @@ -5,7 +5,6 @@ import atexit import os -import platform import sys from contextlib import contextmanager from queue import Empty diff --git a/ipykernel/trio_runner.py b/ipykernel/trio_runner.py index b6d71183e..c72f6455e 100644 --- a/ipykernel/trio_runner.py +++ b/ipykernel/trio_runner.py @@ -17,7 +17,7 @@ def initialize(self, kernel, io_loop): kernel.shell.set_trio_runner(self) kernel.shell.run_line_magic("autoawait", "trio") kernel.shell.magics_manager.magics["line"]["autoawait"] = lambda _: warnings.warn( - "Autoawait isn't allowed in Trio " "background loop mode." + "Autoawait isn't allowed in Trio background loop mode." ) bg_thread = threading.Thread(target=io_loop.start, daemon=True, name="TornadoBackground") bg_thread.start() diff --git a/ipykernel/zmqshell.py b/ipykernel/zmqshell.py index c9ae6f769..1d6627cb4 100644 --- a/ipykernel/zmqshell.py +++ b/ipykernel/zmqshell.py @@ -205,7 +205,7 @@ class KernelMagics(Magics): _find_edit_target = CodeMagics._find_edit_target @line_magic - def edit(self, parameter_s="", last_call=["", ""]): + def edit(self, parameter_s="", last_call=None): """Bring up an editor and execute the resulting code. Usage: @@ -281,7 +281,7 @@ def edit(self, parameter_s="", last_call=["", ""]): Note that %edit is also available through the alias %ed. """ - + last_call = last_call or ["", ""] opts, args = self.parse_options(parameter_s, "prn:") try: