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

Update ruff #1230

Merged
merged 2 commits into from
Mar 6, 2023
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ repos:
- id: black

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.242
rev: v0.0.254
hooks:
- id: ruff
args: ["--fix"]
11 changes: 5 additions & 6 deletions jupyter_server/auth/identity.py
Original file line number Diff line number Diff line change
Expand Up @@ -520,12 +520,11 @@ def validate_security(
f"{warning} and not using authentication. "
"This is highly insecure and not recommended."
)
else:
if not self.auth_enabled:
app.log.warning(
"All authentication is disabled."
" Anyone who can connect to this server will be able to run code."
)
elif not self.auth_enabled:
app.log.warning(
"All authentication is disabled."
" Anyone who can connect to this server will be able to run code."
)

def process_login_form(self, handler: JupyterHandler) -> User | None:
"""Process login form data
Expand Down
11 changes: 5 additions & 6 deletions jupyter_server/auth/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,12 +258,11 @@ def validate_security(cls, app, ssl_options=None):
f"{warning} and not using authentication. "
"This is highly insecure and not recommended."
)
else:
if not app.password and not app.token:
app.log.warning(
"All authentication is disabled."
" Anyone who can connect to this server will be able to run code."
)
elif not app.password and not app.token:
app.log.warning(
"All authentication is disabled."
" Anyone who can connect to this server will be able to run code."
)

@classmethod
def password_from_settings(cls, settings):
Expand Down
6 changes: 3 additions & 3 deletions jupyter_server/base/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@

def json_sys_info():
"""Get sys info as json."""
global _sys_info_cache
global _sys_info_cache # noqa
if _sys_info_cache is None:
_sys_info_cache = json.dumps(get_sys_info())
return _sys_info_cache
Expand Down Expand Up @@ -681,8 +681,8 @@ def write_error(self, status_code, **kwargs):
# get the custom message, if defined
try:
message = exception.log_message % exception.args
except Exception:
pass # noqa
except Exception: # noqa
pass

# construct the custom reason, if defined
reason = getattr(exception, "reason", "")
Expand Down
5 changes: 2 additions & 3 deletions jupyter_server/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,8 @@ def remove_defaults(data, defaults):
remove_defaults(data[key], defaults[key])
if not data[key]: # prune empty subdicts
del data[key]
else:
if value == defaults[key]:
del data[key]
elif value == defaults[key]:
del data[key]


class BaseJSONConfigManager(LoggingConfigurable):
Expand Down
4 changes: 2 additions & 2 deletions jupyter_server/extension/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,9 +214,9 @@ def _default_serverapp(self):
if ServerApp.initialized():
try:
return ServerApp.instance()
except Exception:
except Exception: # noqa
# error retrieving instance, e.g. MultipleInstanceError
pass # noqa
pass

# serverapp accessed before it was defined,
# declare an empty one
Expand Down
7 changes: 3 additions & 4 deletions jupyter_server/files/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,10 @@ async def get(self, path, include_body=True):
self.set_header("Content-Type", "application/octet-stream")
elif cur_mime is not None:
self.set_header("Content-Type", cur_mime)
elif model["format"] == "base64":
self.set_header("Content-Type", "application/octet-stream")
else:
if model["format"] == "base64":
self.set_header("Content-Type", "application/octet-stream")
else:
self.set_header("Content-Type", "text/plain; charset=UTF-8")
self.set_header("Content-Type", "text/plain; charset=UTF-8")

if include_body:
if model["format"] == "base64":
Expand Down
5 changes: 3 additions & 2 deletions jupyter_server/gateway/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,9 @@ async def kernel_culled(self, kernel_id: str) -> bool: # typing: ignore
# Note that should the redundant polling be consolidated, or replaced with an event-based
# notification model, this will need to be revisited.
km = self.kernel_manager.get_kernel(kernel_id)
except Exception: # Let exceptions here reflect culled kernel
pass # noqa
except Exception: # noqa
# Let exceptions here reflect culled kernel
pass
return km is None


Expand Down
15 changes: 7 additions & 8 deletions jupyter_server/serverapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1183,14 +1183,13 @@ def _warn_deprecated_config(self, change, clsname, new_name=None):
f"ServerApp.{change.name} config is deprecated in 2.0. Use {clsname}.{new_name}."
)
self.config[clsname][new_name] = change.new
else:
# Deprecated config used, new config also used.
# Warn only if the values differ.
# If the values are the same, assume intentional backward-compatible config.
if self.config[clsname][new_name] != change.new:
self.log.warning(
f"Ignoring deprecated ServerApp.{change.name} config. Using {clsname}.{new_name}."
)
# Deprecated config used, new config also used.
# Warn only if the values differ.
# If the values are the same, assume intentional backward-compatible config.
elif self.config[clsname][new_name] != change.new:
self.log.warning(
f"Ignoring deprecated ServerApp.{change.name} config. Using {clsname}.{new_name}."
)

@observe("password")
def _deprecated_password(self, change):
Expand Down
2 changes: 1 addition & 1 deletion jupyter_server/services/contents/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def _validate_preferred_dir(self, proposal):
if value != self.parent.preferred_dir:
self.parent.preferred_dir = os.path.join(self.root_dir, *value.split("/"))
except (AttributeError, TraitError):
pass # noqa
pass
return value

allow_hidden = Bool(False, config=True, help="Allow access to hidden files")
Expand Down
26 changes: 12 additions & 14 deletions jupyter_server/services/kernels/connection/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,8 +443,8 @@ def disconnect(self):
try:
ZMQChannelsWebsocketConnection._open_sockets.remove(self)
self._close_future.set_result(None)
except Exception:
pass # noqa
except Exception: # noqa
pass

def handle_incoming_message(self, incoming_msg: str) -> None:
"""Handle incoming messages from Websocket to ZMQ Sockets."""
Expand Down Expand Up @@ -729,12 +729,11 @@ def _limit_rate(self, channel, msg, msg_list): # noqa
),
msg["parent_header"],
)
else:
# resume once we've got some headroom below the limit
if self._iopub_msgs_exceeded and msg_rate < (0.8 * self.iopub_msg_rate_limit):
self._iopub_msgs_exceeded = False
if not self._iopub_data_exceeded:
self.log.warning("iopub messages resumed")
# resume once we've got some headroom below the limit
elif self._iopub_msgs_exceeded and msg_rate < (0.8 * self.iopub_msg_rate_limit):
self._iopub_msgs_exceeded = False
if not self._iopub_data_exceeded:
self.log.warning("iopub messages resumed")

# Check the data rate
if self.iopub_data_rate_limit > 0 and data_rate > self.iopub_data_rate_limit:
Expand All @@ -761,12 +760,11 @@ def _limit_rate(self, channel, msg, msg_list): # noqa
),
msg["parent_header"],
)
else:
# resume once we've got some headroom below the limit
if self._iopub_data_exceeded and data_rate < (0.8 * self.iopub_data_rate_limit):
self._iopub_data_exceeded = False
if not self._iopub_msgs_exceeded:
self.log.warning("iopub messages resumed")
# resume once we've got some headroom below the limit
elif self._iopub_data_exceeded and data_rate < (0.8 * self.iopub_data_rate_limit):
self._iopub_data_exceeded = False
if not self._iopub_msgs_exceeded:
self.log.warning("iopub messages resumed")

# If either of the limit flags are set, do not send the message.
if self._iopub_msgs_exceeded or self._iopub_data_exceeded:
Expand Down
2 changes: 1 addition & 1 deletion jupyter_server/services/kernels/kernelmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ def list_kernels(self):
kernels.append(model)
except (web.HTTPError, KeyError):
# Probably due to a (now) non-existent kernel, continue building the list
pass # noqa
pass
return kernels

# override _check_kernel_id to raise 404 instead of KeyError
Expand Down
4 changes: 2 additions & 2 deletions jupyter_server/services/sessions/sessionmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ async def get_session(self, **kwargs):
raise TypeError(msg)
conditions.append("%s=?" % column)

query = "SELECT * FROM session WHERE %s" % (" AND ".join(conditions))
query = "SELECT * FROM session WHERE %s" % (" AND ".join(conditions)) # noqa

self.cursor.execute(query, list(kwargs.values()))
try:
Expand Down Expand Up @@ -458,7 +458,7 @@ async def update_session(self, session_id, **kwargs):
if column not in self._columns:
raise TypeError("No such column: %r" % column)
sets.append("%s=?" % column)
query = "UPDATE session SET %s WHERE session_id=?" % (", ".join(sets))
query = "UPDATE session SET %s WHERE session_id=?" % (", ".join(sets)) # noqa
self.cursor.execute(query, [*list(kwargs.values()), session_id])

async def kernel_culled(self, kernel_id: str) -> bool:
Expand Down
20 changes: 10 additions & 10 deletions jupyter_server/traittypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ def validate(self, obj, value):
try:
if self.subclass_from_klasses(value):
return value
except Exception:
pass # noqa
except Exception: # noqa
pass

self.error(obj, value)

Expand All @@ -86,7 +86,7 @@ def info(self):
result = "a subclass of "
for klass in self.klasses:
if not isinstance(klass, str):
klass = klass.__module__ + "." + klass.__name__
klass = klass.__module__ + "." + klass.__name__ # noqa
result += f"{klass} or "
# Strip the last "or"
result = result.strip(" or ") # noqa
Expand All @@ -106,10 +106,10 @@ def _resolve_classes(self):
if isinstance(klass, str):
# Try importing the classes to compare. Silently, ignore if not importable.
try:
klass = self._resolve_string(klass)
klass = self._resolve_string(klass) # noqa
self.importable_klasses.append(klass)
except Exception:
pass # noqa
except Exception: # noqa
pass
else:
self.importable_klasses.append(klass)

Expand Down Expand Up @@ -156,7 +156,7 @@ class or its subclasses. Our implementation is quite different
None, the None is replaced by ``()`` or ``{}``, respectively.
"""
# If class
if klasses is None:
if klasses is None: # noqa
self.klasses = klasses
# Verify all elements are either classes or strings.
elif all(inspect.isclass(k) or isinstance(k, str) for k in klasses):
Expand Down Expand Up @@ -218,10 +218,10 @@ def _resolve_classes(self):
if isinstance(klass, str):
# Try importing the classes to compare. Silently, ignore if not importable.
try:
klass = self._resolve_string(klass)
klass = self._resolve_string(klass) # noqa
self.importable_klasses.append(klass)
except Exception:
pass # noqa
except Exception: # noqa
pass
else:
self.importable_klasses.append(klass)

Expand Down
2 changes: 1 addition & 1 deletion jupyter_server/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ def filefind(filename, path_dirs=None):

for path in path_dirs:
if path == ".":
path = os.getcwd()
path = os.getcwd() # noqa
testname = expand_path(os.path.join(path, filename))
if os.path.isfile(testname):
return os.path.abspath(testname)
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ detached = true
dependencies = [
"black[jupyter]==23.1.0",
"mdformat>0.7",
"ruff==0.0.242",
"ruff==0.0.254",
]
[tool.hatch.envs.lint.scripts]
style = [
Expand Down
9 changes: 4 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,10 @@ def pytest_runtest_setup(item):
if item.config.getoption("--integration_tests") is True:
if not is_integration_test:
pytest.skip("Only running tests marked as 'integration_test'.")
else:
if is_integration_test:
pytest.skip(
"Skipping this test because it's marked 'integration_test'. Run integration tests using the `--integration_tests` flag."
)
elif is_integration_test:
pytest.skip(
"Skipping this test because it's marked 'integration_test'. Run integration tests using the `--integration_tests` flag."
)


mock_html = """
Expand Down
2 changes: 1 addition & 1 deletion tests/services/contents/test_fileio.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ class CustomExc(Exception):

@pytest.fixture
def handle_umask():
global umask
global umask # noqa
umask = os.umask(0)
os.umask(umask)
yield
Expand Down