Skip to content

Commit

Permalink
Adopt ruff format (#1161)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Oct 29, 2023
1 parent 2a8adb9 commit 76aca77
Show file tree
Hide file tree
Showing 11 changed files with 64 additions and 78 deletions.
12 changes: 4 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ci:

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-case-conflict
- id: check-ast
Expand Down Expand Up @@ -45,11 +45,6 @@ repos:
- id: blacken-docs
additional_dependencies: [black==23.7.0]

- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.9.1
hooks:
- id: black

- repo: https://github.com/codespell-project/codespell
rev: "v2.2.6"
hooks:
Expand All @@ -64,13 +59,14 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.292
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format

- repo: https://github.com/scientific-python/cookie
rev: "2023.09.21"
rev: "2023.10.27"
hooks:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"]
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
html_theme_options = {"navigation_with_keys": False}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
Expand Down
14 changes: 6 additions & 8 deletions ipykernel/comm/comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def _default_comm_id(self):
return uuid.uuid4().hex

def __init__(
self, target_name='', data=None, metadata=None, buffers=None, show_warning=True, **kwargs
self, target_name="", data=None, metadata=None, buffers=None, show_warning=True, **kwargs
):
"""Initialize a comm."""
if show_warning:
Expand All @@ -85,16 +85,14 @@ def __init__(
)

# Handle differing arguments between base classes.
had_kernel = 'kernel' in kwargs
kernel = kwargs.pop('kernel', None)
had_kernel = "kernel" in kwargs
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]
kwargs["target_name"] = target_name
BaseComm.__init__(self, data=data, metadata=metadata, buffers=buffers, **kwargs) # type:ignore[call-arg]
# only re-add kernel if explicitly provided
if had_kernel:
kwargs['kernel'] = kernel
kwargs["kernel"] = kernel
traitlets.config.LoggingConfigurable.__init__(self, **kwargs)


Expand Down
42 changes: 20 additions & 22 deletions ipykernel/eventloops.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def process_stream_events():
if not hasattr(kernel, "_qt_notifier"):
fd = kernel.shell_stream.getsockopt(zmq.FD)
kernel._qt_notifier = QtCore.QSocketNotifier(
fd, enum_helper('QtCore.QSocketNotifier.Type').Read, kernel.app.qt_event_loop
fd, enum_helper("QtCore.QSocketNotifier.Type").Read, kernel.app.qt_event_loop
)
kernel._qt_notifier.activated.connect(process_stream_events)
else:
Expand Down Expand Up @@ -125,7 +125,7 @@ def loop_qt(kernel):

# `exec` blocks until there's ZMQ activity.
el = kernel.app.qt_event_loop # for brevity
el.exec() if hasattr(el, 'exec') else el.exec_()
el.exec() if hasattr(el, "exec") else el.exec_()
kernel.app._in_event_loop = False


Expand Down Expand Up @@ -465,24 +465,24 @@ def set_qt_api_env_from_gui(gui):
loaded = loaded_api()

qt_env2gui = {
QT_API_PYSIDE2: 'qt5',
QT_API_PYQT5: 'qt5',
QT_API_PYSIDE6: 'qt6',
QT_API_PYQT6: 'qt6',
QT_API_PYSIDE2: "qt5",
QT_API_PYQT5: "qt5",
QT_API_PYSIDE6: "qt6",
QT_API_PYQT6: "qt6",
}
if loaded is not None and gui != 'qt' and qt_env2gui[loaded] != gui:
print(f'Cannot switch Qt versions for this session; you must use {qt_env2gui[loaded]}.')
if loaded is not None and gui != "qt" and qt_env2gui[loaded] != gui:
print(f"Cannot switch Qt versions for this session; you must use {qt_env2gui[loaded]}.")
return

if qt_api is not None and gui != 'qt':
if qt_api is not None and gui != "qt":
if qt_env2gui[qt_api] != gui:
print(
f'Request for "{gui}" will be ignored because `QT_API` '
f'environment variable is set to "{qt_api}"'
)
return
else:
if gui == 'qt5':
if gui == "qt5":
try:
import PyQt5 # noqa

Expand All @@ -494,7 +494,7 @@ def set_qt_api_env_from_gui(gui):
os.environ["QT_API"] = "pyside2"
except ImportError:
os.environ["QT_API"] = "pyqt5"
elif gui == 'qt6':
elif gui == "qt6":
try:
import PyQt6 # noqa

Expand All @@ -506,10 +506,10 @@ def set_qt_api_env_from_gui(gui):
os.environ["QT_API"] = "pyside6"
except ImportError:
os.environ["QT_API"] = "pyqt6"
elif gui == 'qt':
elif gui == "qt":
# Don't set QT_API; let IPython logic choose the version.
if 'QT_API' in os.environ:
del os.environ['QT_API']
if "QT_API" in os.environ:
del os.environ["QT_API"]
else:
print(f'Unrecognized Qt version: {gui}. Should be "qt5", "qt6", or "qt".')
return
Expand All @@ -519,15 +519,15 @@ def set_qt_api_env_from_gui(gui):
from IPython.external.qt_for_kernel import QtCore, QtGui # noqa
except Exception as e:
# Clear the environment variable for the next attempt.
if 'QT_API' in os.environ:
if "QT_API" in os.environ:
del os.environ["QT_API"]
print(f"QT_API couldn't be set due to error {e}")
return


def make_qt_app_for_kernel(gui, kernel):
"""Sets the `QT_API` environment variable if it isn't already set."""
if hasattr(kernel, 'app'):
if hasattr(kernel, "app"):
# Kernel is already running a Qt event loop, so there's no need to
# create another app for it.
return
Expand Down Expand Up @@ -558,18 +558,16 @@ def enable_gui(gui, kernel=None):
raise RuntimeError(msg)
if gui is None:
# User wants to turn off integration; clear any evidence if Qt was the last one.
if hasattr(kernel, 'app'):
delattr(kernel, 'app')
if hasattr(kernel, "app"):
delattr(kernel, "app")
else:
if gui.startswith('qt'):
if gui.startswith("qt"):
# Prepare the kernel here so any exceptions are displayed in the client.
make_qt_app_for_kernel(gui, kernel)

loop = loop_map[gui]
if (
loop
and kernel.eventloop is not None
and kernel.eventloop is not loop # type:ignore[unreachable]
loop and kernel.eventloop is not None and kernel.eventloop is not loop # type:ignore[unreachable]
):
msg = "Cannot activate multiple GUI eventloops" # type:ignore[unreachable]
raise RuntimeError(msg)
Expand Down
4 changes: 1 addition & 3 deletions ipykernel/inprocess/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,7 @@ def stdin_channel(self):
@property
def control_channel(self):
if self._control_channel is None:
self._control_channel = self.control_channel_class(
self
) # type:ignore[abstract,call-arg]
self._control_channel = self.control_channel_class(self) # type:ignore[abstract,call-arg]
return self._control_channel

@property
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ def _watch_pipe_fd(self):
try:
bts = os.read(self._fid, PIPE_BUFFER_SIZE)
while bts and self._should_watch:
self.write(bts.decode(errors='replace'))
self.write(bts.decode(errors="replace"))
os.write(self._original_stdstream_copy, bts)
bts = os.read(self._fid, PIPE_BUFFER_SIZE)
except Exception:
Expand Down Expand Up @@ -531,7 +531,7 @@ def close(self):
self._should_watch = False
# thread won't wake unless there's something to read
# writing something after _should_watch will not be echoed
os.write(self._original_stdstream_fd, b'\0')
os.write(self._original_stdstream_fd, b"\0")
self.watch_fd_thread.join()
# restore original FDs
os.dup2(self._original_stdstream_copy, self._original_stdstream_fd)
Expand Down
4 changes: 2 additions & 2 deletions ipykernel/ipkernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,9 @@ def __init__(self, **kwargs):
)
self.shell.displayhook.session = self.session # type:ignore[attr-defined]

jupyter_session_name = os.environ.get('JPY_SESSION_NAME')
jupyter_session_name = os.environ.get("JPY_SESSION_NAME")
if jupyter_session_name:
self.shell.user_ns['__session__'] = jupyter_session_name
self.shell.user_ns["__session__"] = jupyter_session_name

self.shell.displayhook.pub_socket = self.iopub_socket # type:ignore[attr-defined]
self.shell.displayhook.topic = self._topic("execute_result") # type:ignore[attr-defined]
Expand Down
18 changes: 7 additions & 11 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -117,17 +117,17 @@ dependencies = ["mypy>=1.6.0", "traitlets>=5.12.0", "ipython>=8.16.1", "jupyter_
test = "mypy --install-types --non-interactive {args}"

[tool.hatch.envs.lint]
dependencies = ["black==23.3.0", "mdformat>0.7", "ruff==0.1.1"]
dependencies = ["mdformat>0.7", "ruff==0.1.3"]
detached = true
[tool.hatch.envs.lint.scripts]
style = [
"ruff {args:.}",
"black --check --diff {args:.}",
"ruff format {args:.}",
"mdformat --check {args:docs *.md}"
]
fmt = [
"black {args:.}",
"ruff --fix {args:.}",
"ruff format {args:.}",
"mdformat {args:docs *.md}"
]

Expand Down Expand Up @@ -229,14 +229,11 @@ omit = [
"ipykernel/pylab/*",
]

[tool.black]
line-length = 100
skip-string-normalization = true
target-version = ["py37"]

[tool.ruff]
target-version = "py37"
target-version = "py38"
line-length = 100

[tool.ruff.lint]
select = [
"A",
"B",
Expand All @@ -248,7 +245,6 @@ select = [
"FBT",
"I",
"ICN",
"ISC",
"N",
"PLC",
"PLE",
Expand Down Expand Up @@ -310,7 +306,7 @@ unfixable = [
"RUF100",
]

[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
# B011 Do not call assert False since python -O removes these calls
# F841 local variable 'foo' is assigned to but never used
# C408 Unnecessary `dict` call
Expand Down
12 changes: 6 additions & 6 deletions tests/test_comm.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def foo(comm, msg):
comm.close()

def fizz(comm, msg):
raise RuntimeError('hi')
raise RuntimeError("hi")

def on_close(msg):
msgs.append(msg)
Expand All @@ -69,15 +69,15 @@ def on_msg(msg):
Kernel.clear_instance()

assert manager.get_comm(comm.comm_id) == comm
assert manager.get_comm('foo') is None
assert manager.get_comm("foo") is None

msg = dict(content=dict(comm_id=comm.comm_id, target_name='foo'))
msg = dict(content=dict(comm_id=comm.comm_id, target_name="foo"))
manager.comm_open(None, None, msg)
assert len(msgs) == 1
msg['content']['target_name'] = 'bar'
msg["content"]["target_name"] = "bar"
manager.comm_open(None, None, msg)
assert len(msgs) == 1
msg = dict(content=dict(comm_id=comm.comm_id, target_name='fizz'))
msg = dict(content=dict(comm_id=comm.comm_id, target_name="fizz"))
manager.comm_open(None, None, msg)
assert len(msgs) == 1

Expand All @@ -86,7 +86,7 @@ def on_msg(msg):
msg = dict(content=dict(comm_id=comm.comm_id))
manager.comm_msg(None, None, msg)
assert len(msgs) == 2
msg['content']['comm_id'] = 'foo'
msg["content"]["comm_id"] = "foo"
manager.comm_msg(None, None, msg)
assert len(msgs) == 2

Expand Down
24 changes: 12 additions & 12 deletions tests/test_eventloop.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@

qt_guis_avail = []

gui_to_module = {'qt6': 'PySide6', 'qt5': 'PyQt5'}
gui_to_module = {"qt6": "PySide6", "qt5": "PyQt5"}


def _get_qt_vers():
"""If any version of Qt is available, this will populate `guis_avail` with 'qt' and 'qtx'. Due
to the import mechanism, we can't import multiple versions of Qt in one session."""
for gui in ['qt6', 'qt5']:
print(f'Trying {gui}')
for gui in ["qt6", "qt5"]:
print(f"Trying {gui}")
try:
__import__(gui_to_module[gui])
qt_guis_avail.append(gui)
if 'QT_API' in os.environ:
del os.environ['QT_API']
if "QT_API" in os.environ:
del os.environ["QT_API"]
except ImportError:
pass # that version of Qt isn't available.

Expand Down Expand Up @@ -126,18 +126,18 @@ def test_cocoa_loop(kernel):


@pytest.mark.skipif(
len(qt_guis_avail) == 0, reason='No viable version of PyQt or PySide installed.'
len(qt_guis_avail) == 0, reason="No viable version of PyQt or PySide installed."
)
def test_qt_enable_gui(kernel, capsys):
gui = qt_guis_avail[0]

enable_gui(gui, kernel)

# We store the `QApplication` instance in the kernel.
assert hasattr(kernel, 'app')
assert hasattr(kernel, "app")

# And the `QEventLoop` is added to `app`:`
assert hasattr(kernel.app, 'qt_event_loop')
assert hasattr(kernel.app, "qt_event_loop")

# Don't create another app even if `gui` is the same.
app = kernel.app
Expand All @@ -146,18 +146,18 @@ def test_qt_enable_gui(kernel, capsys):

# Event loop integration can be turned off.
enable_gui(None, kernel)
assert not hasattr(kernel, 'app')
assert not hasattr(kernel, "app")

# But now we're stuck with this version of Qt for good; can't switch.
for not_gui in ['qt6', 'qt5']:
for not_gui in ["qt6", "qt5"]:
if not_gui not in qt_guis_avail:
break

enable_gui(not_gui, kernel)
captured = capsys.readouterr()
assert captured.out == f'Cannot switch Qt versions for this session; you must use {gui}.\n'
assert captured.out == f"Cannot switch Qt versions for this session; you must use {gui}.\n"

# Check 'qt' gui, which means "the best available"
enable_gui(None, kernel)
enable_gui('qt', kernel)
enable_gui("qt", kernel)
assert gui_to_module[gui] in str(kernel.app)
Loading

0 comments on commit 76aca77

Please sign in to comment.