Skip to content

Commit 6cb783c

Browse files
committed
Enable SIM105 (use contextlib.suppress)
1 parent 3a5e1f1 commit 6cb783c

File tree

15 files changed

+44
-58
lines changed

15 files changed

+44
-58
lines changed

pyproject.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,6 @@ ignore = [
268268
# flake8-simplify
269269
"SIM102", # nested 'if' statements
270270
"SIM103", # return condition directly
271-
"SIM105", # use contextlib.suppress
272271
"SIM108", # use ternary operator
273272
# flake8-self
274273
"SLF001", # private member accessed

sphinx/builders/html/__init__.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
import hashlib
67
import html
78
import os
@@ -578,12 +579,11 @@ def get_doc_context(self, docname: str, body: str, metatags: str) -> dict[str, A
578579
# that gracefully
579580
prev = None
580581
while related and related[0]:
581-
try:
582+
with contextlib.suppress(KeyError):
582583
parents.append(
583584
{'link': self.get_relative_uri(docname, related[0]),
584585
'title': self.render_partial(titles[related[0]])['title']})
585-
except KeyError:
586-
pass
586+
587587
related = self.relations.get(related[0])
588588
if parents:
589589
# remove link to the master file; we have a generic
@@ -1102,7 +1102,7 @@ def js_tag(js: _JavaScript | str) -> str:
11021102
templatename = newtmpl
11031103

11041104
# sort JS/CSS before rendering HTML
1105-
try:
1105+
try: # NoQA: SIM105
11061106
# Convert script_files to list to support non-list script_files (refs: #8889)
11071107
ctx['script_files'] = sorted(ctx['script_files'], key=lambda js: js.priority)
11081108
except AttributeError:
@@ -1112,10 +1112,8 @@ def js_tag(js: _JavaScript | str) -> str:
11121112
# Note: priority sorting feature will not work in this case.
11131113
pass
11141114

1115-
try:
1115+
with contextlib.suppress(AttributeError):
11161116
ctx['css_files'] = sorted(ctx['css_files'], key=lambda css: css.priority)
1117-
except AttributeError:
1118-
pass
11191117

11201118
try:
11211119
output = self.templates.render(templatename, ctx)

sphinx/builders/linkcheck.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
import json
67
import re
78
import socket
@@ -304,14 +305,12 @@ def run(self) -> None:
304305
break
305306

306307
netloc = urlsplit(uri).netloc
307-
try:
308+
with contextlib.suppress(KeyError):
308309
# Refresh rate limit.
309310
# When there are many links in the queue, workers are all stuck waiting
310311
# for responses, but the builder keeps queuing. Links in the queue may
311312
# have been queued before rate limits were discovered.
312313
next_check = self.rate_limits[netloc].next_check
313-
except KeyError:
314-
pass
315314
if next_check > time.time():
316315
# Sleep before putting message back in the queue to avoid
317316
# waking up other threads.

sphinx/cmd/build.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import argparse
66
import bdb
7+
import contextlib
78
import locale
89
import multiprocessing
910
import os
@@ -265,10 +266,9 @@ def _parse_arguments(argv: list[str] = sys.argv[1:]) -> argparse.Namespace:
265266
key, val = val.split('=')
266267
except ValueError:
267268
parser.error(__('-A option argument must be in the form name=value'))
268-
try:
269+
with contextlib.suppress(ValueError):
269270
val = int(val)
270-
except ValueError:
271-
pass
271+
272272
confoverrides['html_context.%s' % key] = val
273273

274274
if args.nitpicky:

sphinx/domains/javascript.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
from typing import TYPE_CHECKING, Any, cast
67

78
from docutils import nodes
@@ -218,10 +219,9 @@ def after_content(self) -> None:
218219
"""
219220
objects = self.env.ref_context.setdefault('js:objects', [])
220221
if self.allow_nesting:
221-
try:
222+
with contextlib.suppress(IndexError):
222223
objects.pop()
223-
except IndexError:
224-
pass
224+
225225
self.env.ref_context['js:object'] = (objects[-1] if len(objects) > 0
226226
else None)
227227

sphinx/domains/python.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import ast
66
import builtins
7+
import contextlib
78
import inspect
89
import re
910
import token
@@ -912,10 +913,9 @@ def after_content(self) -> None:
912913
"""
913914
classes = self.env.ref_context.setdefault('py:classes', [])
914915
if self.allow_nesting:
915-
try:
916+
with contextlib.suppress(IndexError):
916917
classes.pop()
917-
except IndexError:
918-
pass
918+
919919
self.env.ref_context['py:class'] = (classes[-1] if len(classes) > 0
920920
else None)
921921
if 'module' in self.options:

sphinx/events.py

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

66
from __future__ import annotations
77

8+
import contextlib
89
from collections import defaultdict
910
from operator import attrgetter
1011
from typing import TYPE_CHECKING, Any, Callable, NamedTuple
@@ -82,12 +83,11 @@ def disconnect(self, listener_id: int) -> None:
8283
def emit(self, name: str, *args: Any,
8384
allowed_exceptions: tuple[type[Exception], ...] = ()) -> list:
8485
"""Emit a Sphinx event."""
85-
try:
86+
87+
# not every object likes to be repr()'d (think
88+
# random stuff coming via autodoc)
89+
with contextlib.suppress(Exception):
8690
logger.debug('[app] emitting event: %r%s', name, repr(args)[:100])
87-
except Exception:
88-
# not every object likes to be repr()'d (think
89-
# random stuff coming via autodoc)
90-
pass
9191

9292
results = []
9393
listeners = sorted(self.listeners[name], key=attrgetter("priority"))

sphinx/ext/githubpages.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import contextlib
56
import os
67
import urllib.parse
78
from typing import TYPE_CHECKING, Any
@@ -47,10 +48,8 @@ def create_nojekyll_and_cname(app: Sphinx, env: BuildEnvironment) -> None:
4748
# auto-generated by the GitHub UI doesn't have one.
4849
f.write(domain)
4950
else:
50-
try:
51+
with contextlib.suppress(FileNotFoundError):
5152
os.unlink(cname_path)
52-
except FileNotFoundError:
53-
pass
5453

5554

5655
def setup(app: Sphinx) -> dict[str, Any]:

sphinx/ext/imgmath.py

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

55
import base64
6+
import contextlib
67
import re
78
import shutil
89
import subprocess
@@ -298,18 +299,14 @@ def clean_up_files(app: Sphinx, exc: Exception) -> None:
298299
return
299300

300301
if hasattr(app.builder, '_imgmath_tempdir'):
301-
try:
302+
with contextlib.suppress(Exception):
302303
shutil.rmtree(app.builder._imgmath_tempdir)
303-
except Exception:
304-
pass
305304

306305
if app.builder.config.imgmath_embed:
307306
# in embed mode, the images are still generated in the math output dir
308307
# to be shared across workers, but are not useful to the final document
309-
try:
308+
with contextlib.suppress(Exception):
310309
shutil.rmtree(path.join(app.builder.outdir, app.builder.imagedir, 'math'))
311-
except Exception:
312-
pass
313310

314311

315312
def get_tooltip(self: HTML5Translator, node: Element) -> str:

sphinx/ext/napoleon/docstring.py

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

55
import collections
6+
import contextlib
67
import inspect
78
import re
89
from functools import partial
@@ -609,10 +610,9 @@ def _parse(self) -> None:
609610

610611
if self._name and self._what in ('attribute', 'data', 'property'):
611612
res: list[str] = []
612-
try:
613+
with contextlib.suppress(StopIteration):
613614
res = self._parse_attribute_docstring()
614-
except StopIteration:
615-
pass
615+
616616
self._parsed_lines.extend(res)
617617
return
618618

0 commit comments

Comments
 (0)