Skip to content

Commit 949085e

Browse files
authored
Update ruff config (#429)
* Update ruff config * fix import
1 parent f9a651d commit 949085e

23 files changed

+113
-126
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ repos:
2121
- id: trailing-whitespace
2222

2323
- repo: https://github.com/python-jsonschema/check-jsonschema
24-
rev: 0.27.2
24+
rev: 0.27.3
2525
hooks:
2626
- id: check-github-workflows
2727

@@ -77,7 +77,7 @@ repos:
7777
]
7878

7979
- repo: https://github.com/astral-sh/ruff-pre-commit
80-
rev: v0.1.6
80+
rev: v0.1.7
8181
hooks:
8282
- id: ruff
8383
types_or: [python, jupyter]

docs/source/conf.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,12 @@
2323
HERE = osp.abspath(osp.dirname(__file__))
2424
sys.path.insert(0, osp.join(HERE, "..", ".."))
2525

26-
from jupyterlab_server import LabServerApp, _version # noqa
26+
from jupyterlab_server import LabServerApp, _version # noqa: E402
2727

2828
# -- Project information -----------------------------------------------------
2929

3030
project = "JupyterLab Server"
31-
copyright = "2021, Project Jupyter" # noqa
31+
copyright = "2021, Project Jupyter"
3232
author = "Project Jupyter"
3333

3434
# The short X.Y version.
@@ -53,7 +53,7 @@
5353
]
5454

5555
try:
56-
import enchant # type:ignore # noqa
56+
import enchant # noqa: F401
5757

5858
extensions += ["sphinxcontrib.spelling"]
5959
except ImportError:
@@ -131,7 +131,7 @@
131131
"""
132132

133133

134-
def setup(app):
134+
def setup(app): # noqa: ARG001
135135
dest = osp.join(HERE, "changelog.md")
136136
shutil.copy(osp.join(HERE, "..", "..", "CHANGELOG.md"), dest)
137137
destination = osp.join(HERE, "api/app-config.rst")

jupyterlab_server/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from .app import LabServerApp
77
from .handlers import LabConfig, LabHandler, add_handlers
88
from .licenses_app import LicensesApp
9-
from .spec import get_openapi_spec, get_openapi_spec_dict # noqa
9+
from .spec import get_openapi_spec, get_openapi_spec_dict # noqa: F401
1010
from .translation_utils import translator
1111
from .workspaces_app import WorkspaceExportApp, WorkspaceImportApp, WorkspaceListApp
1212
from .workspaces_handler import WORKSPACE_EXTENSION, slugify

jupyterlab_server/app.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,13 +93,14 @@ def _deprecated_trait(self, change: Any) -> None:
9393
# protects backward-compatible config from warnings
9494
# if they set the same value under both names
9595
self.log.warning(
96-
"{cls}.{old} is deprecated in JupyterLab {version}, use {cls}.{new} instead".format(
97-
cls=self.__class__.__name__,
98-
old=old_attr,
99-
new=new_attr,
100-
version=version,
101-
)
96+
"%s.%s is deprecated in JupyterLab %s, use %s.%s instead",
97+
self.__class__.__name__,
98+
old_attr,
99+
version,
100+
self.__class__.__name__,
101+
new_attr,
102102
)
103+
103104
setattr(self, new_attr, change.new)
104105

105106
def initialize_settings(self) -> None:

jupyterlab_server/config.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ def get_federated_extensions(labextensions_path: list[str]) -> dict[str, Any]:
7474

7575

7676
def get_static_page_config(
77-
app_settings_dir: str | None = None, logger: Logger | None = None, level: str = "all"
77+
app_settings_dir: str | None = None, # noqa: ARG001
78+
logger: Logger | None = None, # noqa: ARG001
79+
level: str = "all",
7880
) -> dict[str, Any]:
7981
"""Get the static page config for JupyterLab
8082
@@ -105,11 +107,10 @@ def load_config(path: str) -> Any:
105107
with open(path, encoding="utf-8") as fid:
106108
if path.endswith(".json5"):
107109
return json5.load(fid)
108-
else:
109-
return json.load(fid)
110+
return json.load(fid)
110111

111112

112-
def get_page_config( # noqa: PLR0915
113+
def get_page_config(
113114
labextensions_path: list[str], app_settings_dir: str | None = None, logger: Logger | None = None
114115
) -> dict[str, Any]:
115116
"""Get the page config for the application handler"""
@@ -151,7 +152,7 @@ def get_page_config( # noqa: PLR0915
151152
for _, ext_data in federated_exts.items():
152153
if "_build" not in ext_data["jupyterlab"]:
153154
if logger:
154-
logger.warning("%s is not a valid extension" % ext_data["name"])
155+
logger.warning("%s is not a valid extension", ext_data["name"])
155156
continue
156157
extbuild = ext_data["jupyterlab"]["_build"]
157158
extension = {"name": ext_data["name"], "load": extbuild["load"]}

jupyterlab_server/handlers.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def is_url(url: str) -> bool:
6666
class LabHandler(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
6767
"""Render the JupyterLab View."""
6868

69-
@lru_cache() # noqa
69+
@lru_cache # noqa: B019
7070
def get_page_config(self) -> dict[str, Any]:
7171
"""Construct the page config object"""
7272
self.application.store_id = getattr( # type:ignore[attr-defined]
@@ -105,7 +105,7 @@ def get_page_config(self) -> dict[str, Any]:
105105
.relative_to(server_root)
106106
.as_posix()
107107
)
108-
except Exception: # noqa S110
108+
except Exception: # noqa: S110
109109
pass
110110
# JupyterLab relies on an unset/default path being "/"
111111
page_config["preferredPath"] = preferred_path or "/"
@@ -176,15 +176,15 @@ def get(
176176
class NotFoundHandler(LabHandler):
177177
"""A handler for page not found."""
178178

179-
@lru_cache() # noqa
179+
@lru_cache # noqa: B019
180180
def get_page_config(self) -> dict[str, Any]:
181181
"""Get the page config."""
182182
page_config = super().get_page_config()
183183
page_config["notFoundUrl"] = self.request.path
184184
return page_config
185185

186186

187-
def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # noqa
187+
def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None:
188188
"""Add the appropriate handlers to the web app."""
189189
# Normalize directories.
190190
for name in LabConfig.class_trait_names():
@@ -272,8 +272,9 @@ def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # n
272272
allowed_extensions_uris: str = settings_config.get("allowed_extensions_uris", "")
273273

274274
if (blocked_extensions_uris) and (allowed_extensions_uris):
275-
warnings.warn( # noqa B028
276-
"Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those."
275+
warnings.warn(
276+
"Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those.",
277+
stacklevel=2,
277278
)
278279
import sys
279280

@@ -339,7 +340,7 @@ def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # n
339340
handlers.append((fallthrough_url, NotFoundHandler))
340341

341342

342-
def _camelCase(base: str) -> str: # noqa
343+
def _camelCase(base: str) -> str:
343344
"""Convert a string to camelCase.
344345
https://stackoverflow.com/a/20744956
345346
"""

jupyterlab_server/licenses_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@ def report(self, report_format: str, bundles_pattern: str, full_text: bool) -> t
8787
bundles = self.bundles(bundles_pattern=bundles_pattern)
8888
if report_format == "json":
8989
return self.report_json(bundles), "application/json"
90-
elif report_format == "csv":
90+
if report_format == "csv":
9191
return self.report_csv(bundles), "text/csv"
92-
elif report_format == "markdown":
92+
if report_format == "markdown":
9393
return (
9494
self.report_markdown(bundles, full_text=full_text),
9595
"text/markdown",

jupyterlab_server/listings_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def fetch_listings(logger: Logger | None) -> None:
2525
blocked_extensions = []
2626
for blocked_extensions_uri in ListingsHandler.blocked_extensions_uris:
2727
logger.info(
28-
f"Fetching blocked_extensions from {ListingsHandler.blocked_extensions_uris}"
28+
"Fetching blocked_extensions from %s", ListingsHandler.blocked_extensions_uris
2929
)
3030
r = requests.request(
3131
"GET", blocked_extensions_uri, **ListingsHandler.listings_request_opts
@@ -38,7 +38,7 @@ def fetch_listings(logger: Logger | None) -> None:
3838
allowed_extensions = []
3939
for allowed_extensions_uri in ListingsHandler.allowed_extensions_uris:
4040
logger.info(
41-
f"Fetching allowed_extensions from {ListingsHandler.allowed_extensions_uris}"
41+
"Fetching allowed_extensions from %s", ListingsHandler.allowed_extensions_uris
4242
)
4343
r = requests.request(
4444
"GET", allowed_extensions_uri, **ListingsHandler.listings_request_opts

jupyterlab_server/process.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def __init__(
106106
self.logger = logger or self.get_log()
107107
self._last_line = ""
108108
if not quiet:
109-
self.logger.info(f"> {list2cmdline(cmd)}")
109+
self.logger.info("> %s", list2cmdline(cmd))
110110
self.cmd = cmd
111111

112112
kwargs = {}
@@ -130,7 +130,7 @@ def terminate(self) -> int:
130130
try:
131131
proc.wait(timeout=2.0)
132132
except subprocess.TimeoutExpired:
133-
if os.name == "nt": # noqa
133+
if os.name == "nt": # noqa: SIM108
134134
sig = signal.SIGBREAK # type:ignore[attr-defined]
135135
else:
136136
sig = signal.SIGKILL
@@ -185,8 +185,7 @@ def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:
185185
if os.name == "nt":
186186
kwargs["shell"] = True
187187

188-
proc = subprocess.Popen(cmd, **kwargs) # noqa
189-
return proc
188+
return subprocess.Popen(cmd, **kwargs) # noqa: S603
190189

191190
@classmethod
192191
def _cleanup(cls: type[Process]) -> None:
@@ -278,10 +277,10 @@ def _read_incoming(self) -> None:
278277
buf = os.read(fileno, 1024)
279278
except OSError as e:
280279
self.logger.debug("Read incoming error %s", e)
281-
return None
280+
return
282281

283282
if not buf:
284-
return None
283+
return
285284

286285
print(buf.decode("utf-8"), end="")
287286

jupyterlab_server/pytest_plugin.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def make_labserver_extension_app(
4949
) -> Callable[..., LabServerApp]:
5050
"""Return a factory function for a labserver extension app."""
5151

52-
def _make_labserver_extension_app(**kwargs: Any) -> LabServerApp:
52+
def _make_labserver_extension_app(**kwargs: Any) -> LabServerApp: # noqa: ARG001
5353
"""Factory function for lab server extension apps."""
5454
return LabServerApp(
5555
static_dir=str(jp_root_dir),

jupyterlab_server/settings_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def initialize( # type:ignore[override]
2525
schemas_dir: str,
2626
settings_dir: str,
2727
labextensions_path: list[str],
28-
**kwargs: Any,
28+
**kwargs: Any, # noqa: ARG002
2929
) -> None:
3030
"""Initialize the handler."""
3131
SchemaHandler.initialize(

jupyterlab_server/settings_utils.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ def _list_settings(
157157
return ([], warnings)
158158

159159
schema_pattern = schemas_dir + "/**/*" + extension
160-
schema_paths = [path for path in glob(schema_pattern, recursive=True)]
160+
schema_paths = [path for path in glob(schema_pattern, recursive=True)] # noqa: C416
161161
schema_paths.sort()
162162

163163
for schema_path in schema_paths:
@@ -186,7 +186,7 @@ def _list_settings(
186186
schema_paths = []
187187
for ext_dir in labextensions_path:
188188
schema_pattern = ext_dir + "/**/schemas/**/*" + extension
189-
schema_paths.extend([path for path in glob(schema_pattern, recursive=True)])
189+
schema_paths.extend(path for path in glob(schema_pattern, recursive=True))
190190

191191
schema_paths.sort()
192192

@@ -460,7 +460,7 @@ def initialize(
460460

461461
if error:
462462
overrides_warning = "Failed loading overrides: %s"
463-
self.log.warning(overrides_warning % str(error))
463+
self.log.warning(overrides_warning, error)
464464

465465
def get_current_locale(self) -> str:
466466
"""
@@ -486,7 +486,7 @@ def get_current_locale(self) -> str:
486486
)
487487
except web.HTTPError as e:
488488
schema_warning = "Missing or misshapen translation settings schema:\n%s"
489-
self.log.warning(schema_warning % str(e))
489+
self.log.warning(schema_warning, e)
490490

491491
settings = {}
492492

jupyterlab_server/test_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def maybe_patch_ioloop() -> None:
174174
set_event_loop_policy(WindowsSelectorEventLoopPolicy())
175175

176176

177-
def expected_http_error( # noqa: PLR0911
177+
def expected_http_error(
178178
error: Exception, expected_code: int, expected_message: str | None = None
179179
) -> bool:
180180
"""Check that the error matches the expected output error."""
@@ -185,7 +185,7 @@ def expected_http_error( # noqa: PLR0911
185185
if expected_message is not None and expected_message != str(e):
186186
return False
187187
return True
188-
elif any(
188+
if any(
189189
[
190190
isinstance(e, tornado.httpclient.HTTPClientError),
191191
isinstance(e, tornado.httpclient.HTTPError),

jupyterlab_server/themes_handler.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,15 @@ def initialize(
2424
no_cache_paths: list[str] | None = None,
2525
themes_url: str | None = None,
2626
labextensions_path: list[str] | None = None,
27-
**kwargs: Any,
27+
**kwargs: Any, # noqa: ARG002
2828
) -> None:
2929
"""Initialize the handler."""
3030
# Get all of the available theme paths in order
3131
labextensions_path = labextensions_path or []
32-
ext_paths = []
32+
ext_paths: list[str] = []
3333
for ext_dir in labextensions_path:
3434
theme_pattern = ext_dir + "/**/themes"
35-
ext_paths.extend([path for path in glob(theme_pattern, recursive=True)])
35+
ext_paths.extend(path for path in glob(theme_pattern, recursive=True))
3636

3737
# Add the core theme path last
3838
if not isinstance(path, list):
@@ -65,8 +65,7 @@ def get_content_size(self) -> int:
6565
base, ext = os.path.splitext(self.absolute_path)
6666
if ext != ".css":
6767
return FileFindHandler.get_content_size(self)
68-
else:
69-
return len(self._get_css())
68+
return len(self._get_css())
7069

7170
def _get_css(self) -> bytes:
7271
"""Get the mangled css file contents."""

jupyterlab_server/translation_utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -412,7 +412,7 @@ def update_locale(self, locale_: str) -> None:
412412
mod = importlib.import_module(language_pack_module)
413413
assert mod.__file__ is not None
414414
localedir = os.path.join(os.path.dirname(mod.__file__), LOCALE_DIR)
415-
except Exception: # noqa S110
415+
except Exception: # noqa: S110
416416
# no-op
417417
pass
418418

@@ -588,7 +588,7 @@ def _np(self, msgctxt: str, msgid: str, msgid_plural: str, n: int) -> str:
588588
return self.npgettext(msgctxt, msgid, msgid_plural, n)
589589

590590

591-
class translator: # noqa
591+
class translator:
592592
"""
593593
Translations manager.
594594
"""
@@ -673,7 +673,7 @@ def _translate_schema_strings(
673673

674674
if isinstance(value, str):
675675
matched = False
676-
for pattern, context in to_translate.items(): # noqa
676+
for pattern, context in to_translate.items(): # noqa: B007
677677
if pattern.fullmatch(path):
678678
matched = True
679679
break

0 commit comments

Comments
 (0)