Skip to content

Commit 0983b71

Browse files
authored
Update ruff and typings (#1365)
1 parent ea6ceee commit 0983b71

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

75 files changed

+207
-272
lines changed

.pre-commit-config.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ repos:
3333
[mdformat-gfm, mdformat-frontmatter, mdformat-footnote]
3434

3535
- repo: https://github.com/pre-commit/mirrors-prettier
36-
rev: "v3.0.3"
36+
rev: "v3.1.0"
3737
hooks:
3838
- id: prettier
3939
types_or: [yaml, html, json]
@@ -58,7 +58,7 @@ repos:
5858
- id: rst-inline-touching-normal
5959

6060
- repo: https://github.com/pre-commit/mirrors-mypy
61-
rev: "v1.6.1"
61+
rev: "v1.7.0"
6262
hooks:
6363
- id: mypy
6464
files: jupyter_server
@@ -67,7 +67,7 @@ repos:
6767
["traitlets>=5.13", "jupyter_core>=5.5", "jupyter_client>=8.5"]
6868

6969
- repo: https://github.com/astral-sh/ruff-pre-commit
70-
rev: v0.1.5
70+
rev: v0.1.6
7171
hooks:
7272
- id: ruff
7373
types_or: [python, jupyter]
@@ -76,7 +76,7 @@ repos:
7676
types_or: [python, jupyter]
7777

7878
- repo: https://github.com/scientific-python/cookie
79-
rev: "2023.10.27"
79+
rev: "2023.11.17"
8080
hooks:
8181
- id: sp-repo-review
8282
additional_dependencies: ["repo-review[cli]"]

docs/source/conf.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
#!/usr/bin/env python3
2-
#
31
# Jupyter Server documentation build configuration file, created by
42
# sphinx-quickstart on Mon Apr 13 09:51:11 2015.
53
#
@@ -44,7 +42,7 @@
4442
]
4543

4644
try:
47-
import enchant # type:ignore[import-not-found] # noqa
45+
import enchant # type:ignore[import-not-found]
4846

4947
extensions += ["sphinxcontrib.spelling"]
5048
except ImportError:
@@ -338,7 +336,7 @@
338336
spelling_word_list_filename = "spelling_wordlist.txt"
339337

340338
# import before any doc is built, so _ is guaranteed to be injected
341-
import jupyter_server.transutils # noqa: F401
339+
import jupyter_server.transutils
342340

343341
CONFIG_HEADER = """\
344342
.. _other-full-config:

examples/simple/simple_ext1/application.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ class SimpleApp1(ExtensionAppJinjaMixin, ExtensionApp):
3636
# Local path to templates directory.
3737
template_paths = [DEFAULT_TEMPLATE_FILES_PATH] # type:ignore[assignment]
3838

39-
configA = Unicode("", config=True, help="Config A example.") # noqa
39+
configA = Unicode("", config=True, help="Config A example.")
4040

41-
configB = Unicode("", config=True, help="Config B example.") # noqa
41+
configB = Unicode("", config=True, help="Config B example.")
4242

43-
configC = Unicode("", config=True, help="Config C example.") # noqa
43+
configC = Unicode("", config=True, help="Config C example.")
4444

4545
def initialize_handlers(self):
4646
"""Initialize handlers."""

examples/simple/simple_ext1/handlers.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,6 @@ def get(self, matched_part=None, *args, **kwargs):
4747
class BaseTemplateHandler(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
4848
"""The base template handler."""
4949

50-
pass
51-
5250

5351
class TypescriptHandler(BaseTemplateHandler):
5452
"""A typescript handler."""

examples/simple/simple_ext2/application.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class SimpleApp2(ExtensionAppJinjaMixin, ExtensionApp):
2929
# Local path to templates directory.
3030
template_paths = [DEFAULT_TEMPLATE_FILES_PATH] # type:ignore[assignment]
3131

32-
configD = Unicode("", config=True, help="Config D example.") # noqa
32+
configD = Unicode("", config=True, help="Config D example.")
3333

3434
def initialize_handlers(self):
3535
"""Initialize handlers."""

examples/simple/simple_ext2/handlers.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ def get(self, matched_part=None, *args, **kwargs):
2020
class BaseTemplateHandler(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
2121
"""A base template handler."""
2222

23-
pass
24-
2523

2624
class IndexHandler(BaseTemplateHandler):
2725
"""The root API handler."""

examples/simple/tests/test_handlers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import pytest
33

44

5-
@pytest.fixture
5+
@pytest.fixture()
66
def jp_server_auth_resources(jp_server_auth_core_resources):
77
"""The server auth resources."""
88
for url_regex in [
@@ -12,7 +12,7 @@ def jp_server_auth_resources(jp_server_auth_core_resources):
1212
return jp_server_auth_core_resources
1313

1414

15-
@pytest.fixture
15+
@pytest.fixture()
1616
def jp_server_config(jp_template_dir, jp_server_authorizer):
1717
"""The server config."""
1818
return {

jupyter_server/_sysinfo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def pkg_commit_hash(pkg_path):
4141
if p.exists(p.join(cur_path, ".git")):
4242
try:
4343
proc = subprocess.Popen(
44-
["git", "rev-parse", "--short", "HEAD"], # noqa
44+
["git", "rev-parse", "--short", "HEAD"],
4545
stdout=subprocess.PIPE,
4646
stderr=subprocess.PIPE,
4747
cwd=pkg_path,

jupyter_server/_tz.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
ZERO = timedelta(0)
1414

1515

16-
class tzUTC(tzinfo): # noqa: N801
16+
class tzUTC(tzinfo):
1717
"""tzinfo object for UTC (zero offset)"""
1818

1919
def utcoffset(self, d: datetime | None) -> timedelta:

jupyter_server/auth/__init__.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .authorizer import * # noqa: F403
2-
from .decorator import authorized # noqa: F401
3-
from .identity import * # noqa: F403
4-
from .security import passwd # noqa: F401
1+
from .authorizer import *
2+
from .decorator import authorized
3+
from .identity import *
4+
from .security import passwd

jupyter_server/auth/__main__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def set_password(args):
2020
password_repeat = getpass("" if args.quiet else "Repeat password: ")
2121
if password1 != password_repeat:
2222
warnings.warn("Passwords do not match, try again", stacklevel=2)
23-
elif len(password1) < 4: # noqa
23+
elif len(password1) < 4:
2424
warnings.warn("Please provide at least 4 characters", stacklevel=2)
2525
else:
2626
password = password1

jupyter_server/auth/identity.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ def is_token_authenticated(self, handler: web.RequestHandler) -> bool:
496496
- skip origin-checks for scripts
497497
"""
498498
# ensure get_user has been called, so we know if we're token-authenticated
499-
handler.current_user # noqa
499+
handler.current_user # noqa: B018
500500
return getattr(handler, "_token_authenticated", False)
501501

502502
def validate_security(

jupyter_server/auth/login.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def is_token_authenticated(cls, handler):
179179
"""DEPRECATED in 2.0, use IdentityProvider API"""
180180
if getattr(handler, "_user_id", None) is None:
181181
# ensure get_user has been called, so we know if we're token-authenticated
182-
handler.current_user # noqa
182+
handler.current_user # noqa: B018
183183
return getattr(handler, "_token_authenticated", False)
184184

185185
@classmethod
@@ -233,7 +233,7 @@ def get_user_token(cls, handler):
233233
"""DEPRECATED in 2.0, use IdentityProvider API"""
234234
token = handler.token
235235
if not token:
236-
return
236+
return None
237237
# check login token from URL argument or Authorization header
238238
user_token = cls.get_token(handler)
239239
authenticated = False

jupyter_server/auth/security.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ def passwd(passphrase=None, algorithm="argon2"):
5252
if p0 == p1:
5353
passphrase = p0
5454
break
55-
else:
56-
warnings.warn("Passwords do not match.", stacklevel=2)
55+
warnings.warn("Passwords do not match.", stacklevel=2)
5756
else:
5857
msg = "No matching passwords found. Giving up."
5958
raise ValueError(msg)

jupyter_server/auth/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,4 +166,4 @@ def get_anonymous_username() -> str:
166166
Get a random user-name based on the moons of Jupyter.
167167
This function returns names like "Anonymous Io" or "Anonymous Metis".
168168
"""
169-
return moons_of_jupyter[random.randint(0, len(moons_of_jupyter) - 1)] # noqa
169+
return moons_of_jupyter[random.randint(0, len(moons_of_jupyter) - 1)]

jupyter_server/base/handlers.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464

6565
def json_sys_info():
6666
"""Get sys info as json."""
67-
global _sys_info_cache # noqa
67+
global _sys_info_cache # noqa: PLW0603
6868
if _sys_info_cache is None:
6969
_sys_info_cache = json.dumps(get_sys_info())
7070
return _sys_info_cache
@@ -527,11 +527,11 @@ def check_xsrf_cookie(self) -> None:
527527
"""Bypass xsrf cookie checks when token-authenticated"""
528528
if not hasattr(self, "_jupyter_current_user"):
529529
# Called too early, will be checked later
530-
return
530+
return None
531531
if self.token_authenticated or self.settings.get("disable_check_xsrf", False):
532532
# Token-authenticated requests do not need additional XSRF-check
533533
# Servers without authentication are vulnerable to XSRF
534-
return
534+
return None
535535
try:
536536
return super().check_xsrf_cookie()
537537
except web.HTTPError as e:
@@ -608,11 +608,11 @@ async def prepare(self) -> Awaitable[None] | None: # type:ignore[override]
608608
# check for overridden get_current_user + default IdentityProvider
609609
# deprecated way to override auth (e.g. JupyterHub < 3.0)
610610
# allow deprecated, overridden get_current_user
611-
warnings.warn( # noqa
611+
warnings.warn(
612612
"Overriding JupyterHandler.get_current_user is deprecated in jupyter-server 2.0."
613613
" Use an IdentityProvider class.",
614614
DeprecationWarning,
615-
# stacklevel not useful here
615+
stacklevel=1,
616616
)
617617
user = User(self.get_current_user())
618618
else:
@@ -695,7 +695,7 @@ def write_error(self, status_code: int, **kwargs: Any) -> None:
695695
# get the custom message, if defined
696696
try:
697697
message = exception.log_message % exception.args
698-
except Exception: # noqa
698+
except Exception:
699699
pass
700700

701701
# construct the custom reason, if defined

jupyter_server/base/websocket.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ def check_origin(self, origin: Optional[str] = None) -> bool:
8181

8282
def clear_cookie(self, *args, **kwargs):
8383
"""meaningless for websockets"""
84-
pass
8584

8685
@no_type_check
8786
def open(self, *args, **kwargs):

jupyter_server/extension/application.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def _preparse_for_subcommand(application_klass, argv):
2828
"""Preparse command line to look for subcommands."""
2929
# Read in arguments from command line.
3030
if len(argv) == 0:
31-
return
31+
return None
3232

3333
# Find any subcommands.
3434
if application_klass.subcommands and len(argv) > 0:
@@ -218,7 +218,7 @@ def _default_serverapp(self):
218218
if ServerApp.initialized():
219219
try:
220220
return ServerApp.instance()
221-
except Exception: # noqa
221+
except Exception:
222222
# error retrieving instance, e.g. MultipleInstanceError
223223
pass
224224

@@ -271,7 +271,7 @@ def _default_static_url_prefix(self):
271271

272272
handlers: List[tuple[t.Any, ...]] = List(
273273
help=_i18n("""Handlers appended to the server.""")
274-
).tag(config=True) # type:ignore[assignment]
274+
).tag(config=True)
275275

276276
def _config_file_name_default(self):
277277
"""The default config file name."""
@@ -281,15 +281,12 @@ def _config_file_name_default(self):
281281

282282
def initialize_settings(self):
283283
"""Override this method to add handling of settings."""
284-
pass
285284

286285
def initialize_handlers(self):
287286
"""Override this method to append handlers to a Jupyter Server."""
288-
pass
289287

290288
def initialize_templates(self):
291289
"""Override this method to add handling of template files."""
292-
pass
293290

294291
def _prepare_config(self):
295292
"""Builds a Config object from the extension's traits and passes
@@ -599,7 +596,7 @@ def launch_instance(cls, argv=None, **kwargs):
599596
extension's landing page.
600597
"""
601598
# Handle arguments.
602-
if argv is None: # noqa
599+
if argv is None: # noqa: SIM108
603600
args = sys.argv[1:] # slice out extension config.
604601
else:
605602
args = argv

jupyter_server/extension/manager.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from __future__ import annotations
33

44
import importlib
5+
from itertools import starmap
56

67
from tornado.gen import multi
78
from traitlets import Any, Bool, Dict, HasTraits, Instance, List, Unicode, default, observe
@@ -392,12 +393,7 @@ def load_all_extensions(self):
392393

393394
async def stop_all_extensions(self):
394395
"""Call the shutdown hooks in all extensions."""
395-
await multi(
396-
[
397-
self.stop_extension(name, apps)
398-
for name, apps in sorted(dict(self.extension_apps).items())
399-
]
400-
)
396+
await multi(list(starmap(self.stop_extension, sorted(dict(self.extension_apps).items()))))
401397

402398
def any_activity(self):
403399
"""Check for any activity currently happening across all extension applications."""

jupyter_server/extension/utils.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,18 @@
77
class ExtensionLoadingError(Exception):
88
"""An extension loading error."""
99

10-
pass
11-
1210

1311
class ExtensionMetadataError(Exception):
1412
"""An extension metadata error."""
1513

16-
pass
17-
1814

1915
class ExtensionModuleNotFound(Exception):
2016
"""An extension module not found error."""
2117

22-
pass
23-
2418

2519
class NotAnExtensionApp(Exception):
2620
"""An error raised when a module is not an extension."""
2721

28-
pass
29-
3022

3123
def get_loader(obj, logger=None):
3224
"""Looks for _load_jupyter_server_extension as an attribute
@@ -36,12 +28,12 @@ def get_loader(obj, logger=None):
3628
underscore prefix.
3729
"""
3830
try:
39-
return getattr(obj, "_load_jupyter_server_extension") # noqa B009
31+
return obj._load_jupyter_server_extension
4032
except AttributeError:
4133
pass
4234

4335
try:
44-
func = getattr(obj, "load_jupyter_server_extension") # noqa B009
36+
func = obj.load_jupyter_server_extension
4537
except AttributeError:
4638
msg = "_load_jupyter_server_extension function was not found."
4739
raise ExtensionLoadingError(msg) from None

jupyter_server/gateway/connections.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ async def _read_messages(self):
104104

105105
# NOTE(esevan): if websocket is not disconnected by client, try to reconnect.
106106
if not self.disconnected and self.retry < GatewayClient.instance().gateway_retry_max:
107-
jitter = random.randint(10, 100) * 0.01 # noqa
107+
jitter = random.randint(10, 100) * 0.01
108108
retry_interval = (
109109
min(
110110
GatewayClient.instance().gateway_retry_interval * (2**self.retry),

0 commit comments

Comments
 (0)