Skip to content

Commit

Permalink
Update ruff config (#2079)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Dec 12, 2023
1 parent fd5bec9 commit a7df9af
Show file tree
Hide file tree
Showing 49 changed files with 159 additions and 178 deletions.
14 changes: 3 additions & 11 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@ jobs:
strategy:
matrix:
os: ["ubuntu-20.04", "macos-latest", "windows-latest"]
python-version: ["3.8", "3.11"]
python-version: ["3.8", "3.12"]
include:
- os: "windows-latest"
python-version: "3.9"
- os: "ubuntu-20.04"
- os: "macos-latest"
python-version: "3.10"
- os: "ubuntu-20.04"
python-version: "3.11"
fail-fast: false
steps:
- uses: actions/checkout@v4
Expand Down Expand Up @@ -57,15 +58,6 @@ jobs:
- uses: jupyterlab/maintainer-tools/.github/actions/upload-coverage@v1

python312:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jupyterlab/maintainer-tools/.github/actions/base-setup@v1
with:
python_version: "3.12"
- run: hatch run test:test

coverage:
runs-on: ubuntu-latest
needs:
Expand Down
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.27.2
rev: 0.27.3
hooks:
- id: check-github-workflows

Expand Down Expand Up @@ -81,7 +81,7 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
rev: v0.1.7
hooks:
- id: ruff
types_or: [python, jupyter]
Expand Down
1 change: 0 additions & 1 deletion docs/autogen_config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
#!/usr/bin/env python
"""
autogen_config.py
Expand Down
10 changes: 4 additions & 6 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
#
# nbconvert documentation build configuration file, created by
# sphinx-quickstart on Tue Jun 9 17:11:30 2015.
#
Expand All @@ -25,7 +23,7 @@

# Automatically generate config_options.rst
with open(os.path.join(HERE, "..", "autogen_config.py")) as f:
exec(compile(f.read(), "autogen_config.py", "exec"), {}) # noqa
exec(compile(f.read(), "autogen_config.py", "exec"), {}) # noqa: S102
print("Created docs for config options")

# -- General configuration ------------------------------------------------
Expand All @@ -47,7 +45,7 @@
]

try:
import enchant # type:ignore # noqa
import enchant # noqa: F401

extensions += ["sphinxcontrib.spelling"]
except ImportError:
Expand All @@ -74,7 +72,7 @@


year = datetime.now(tz=timezone.utc).date().year
copyright = "2015-%s, Jupyter Development Team" % year # noqa
copyright = "2015-%s, Jupyter Development Team" % year
author = "Jupyter Development Team"

extlinks = {"ghpull": ("https://github.com/jupyter/nbconvert/pull/%s", "PR #%s")}
Expand All @@ -90,7 +88,7 @@
# Get information from _version.py and use it to generate version and release
_version_py = os.path.join(HERE, "../../nbconvert/_version.py")
version_ns = {}
exec(compile(open(_version_py).read(), _version_py, "exec"), version_ns) # noqa
exec(compile(open(_version_py).read(), _version_py, "exec"), version_ns) # noqa: SIM115, S102
# The short X.Y version.
version = "%i.%i" % version_ns["version_info"][:2]
# The full version, including alpha/beta/rc tags.
Expand Down
2 changes: 1 addition & 1 deletion hatch_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def _get_css_file(template_name, url, filename):
os.makedirs(directory)
print("Downloading CSS: %s" % url)
try:
css = urlopen(url).read() # noqa
css = urlopen(url).read() # noqa: S310
except Exception as e:
msg = f"Failed to download css from {url}: {e}"
print(msg, file=sys.stderr)
Expand Down
2 changes: 1 addition & 1 deletion nbconvert/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# Build up version_info tuple for backwards compatibility
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
match = re.match(pattern, __version__)
assert match is not None # noqa
assert match is not None
parts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]]
if match["rest"]:
parts.append(match["rest"])
Expand Down
18 changes: 6 additions & 12 deletions nbconvert/exporters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,10 @@
class ExporterNameError(NameError):
"""An exporter name error."""

pass


class ExporterDisabledError(ValueError):
"""An exporter disabled error."""

pass


def export(exporter, nb, **kw):
"""
Expand Down Expand Up @@ -74,7 +70,7 @@ def export(exporter, nb, **kw):
if exporter is None:
msg = "Exporter is None"
raise TypeError(msg)
elif not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
if not isinstance(exporter, Exporter) and not issubclass(exporter, Exporter):
msg = "exporter does not inherit from Exporter (base)"
raise TypeError(msg)
if nb is None:
Expand All @@ -95,7 +91,7 @@ def export(exporter, nb, **kw):
return output, resources


def get_exporter(name, config=get_config()): # noqa
def get_exporter(name, config=get_config()): # noqa: B008
"""Given an exporter name or import path, return a class ready to be instantiated
Raises ExporterName if exporter is not found or ExporterDisabledError if not enabled
Expand All @@ -110,8 +106,7 @@ def get_exporter(name, config=get_config()): # noqa
exporter = items[0].load()
if getattr(exporter(config=config), "enabled", True):
return exporter
else:
raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
except IndexError:
pass

Expand All @@ -120,19 +115,18 @@ def get_exporter(name, config=get_config()): # noqa
exporter = import_item(name)
if getattr(exporter(config=config), "enabled", True):
return exporter
else:
raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
raise ExporterDisabledError('Exporter "%s" disabled in configuration' % (name))
except ImportError:
log = get_logger()
log.error("Error importing %s" % name, exc_info=True)
log.error("Error importing %s", name, exc_info=True) # noqa: G201

msg = 'Unknown exporter "{}", did you mean one of: {}?'.format(
name, ", ".join(get_export_names())
)
raise ExporterNameError(msg)


def get_export_names(config=get_config()): # noqa
def get_export_names(config=get_config()): # noqa: B008
"""Return a list of the currently supported export targets
Exporters can be found in external packages by registering
Expand Down
19 changes: 10 additions & 9 deletions nbconvert/exporters/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,29 +253,30 @@ def register_preprocessor(self, preprocessor, enabled=False):
preprocessor_cls = import_item(preprocessor)
return self.register_preprocessor(preprocessor_cls, enabled)

if constructed and hasattr(preprocessor, "__call__"): # noqa
if constructed and callable(preprocessor):
# Preprocessor is a function, no need to construct it.
# Register and return the preprocessor.
if enabled:
preprocessor.enabled = True
self._preprocessors.append(preprocessor)
return preprocessor

elif isclass and issubclass(preprocessor, HasTraits):
if isclass and issubclass(preprocessor, HasTraits):
# Preprocessor is configurable. Make sure to pass in new default for
# the enabled flag if one was specified.
self.register_preprocessor(preprocessor(parent=self), enabled)
return None

elif isclass:
if isclass:
# Preprocessor is not configurable, construct it
self.register_preprocessor(preprocessor(), enabled)
return None

else:
# Preprocessor is an instance of something without a __call__
# attribute.
raise TypeError(
"preprocessor must be callable or an importable constructor, got %r" % preprocessor
)
# Preprocessor is an instance of something without a __call__
# attribute.
raise TypeError(
"preprocessor must be callable or an importable constructor, got %r" % preprocessor
)

def _init_preprocessors(self):
"""
Expand Down
9 changes: 5 additions & 4 deletions nbconvert/exporters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,9 @@ def default_config(self):
def _valid_language_code(self, proposal):
if self.language_code not in iso639_1:
self.log.warning(
f'"{self.language_code}" is not an ISO 639-1 language code. '
'It has been replaced by the default value "en".'
'"%s" is not an ISO 639-1 language code. '
'It has been replaced by the default value "en".',
self.language_code,
)
return proposal["trait"].default_value
return proposal["value"]
Expand Down Expand Up @@ -265,7 +266,7 @@ def from_notebook_node( # type:ignore[explicit-override, override]
elem.attrs["alt"] = "No description has been provided for this image"
missing_alt += 1
if missing_alt:
self.log.warning(f"Alternative text is missing on {missing_alt} image(s).")
self.log.warning("Alternative text is missing on %s image(s).", missing_alt)
# Set input and output focusable
for elem in soup.select(".jp-Notebook div.jp-Cell-inputWrapper"):
elem.attrs["tabindex"] = "0"
Expand All @@ -274,7 +275,7 @@ def from_notebook_node( # type:ignore[explicit-override, override]

return str(soup), resources

def _init_resources(self, resources): # noqa
def _init_resources(self, resources):
def resources_include_css(name):
env = self.environment
code = """<style type="text/css">\n%s</style>""" % (env.loader.get_source(env, name)[0])
Expand Down
13 changes: 5 additions & 8 deletions nbconvert/exporters/pdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from .latex import LatexExporter


class LatexFailed(IOError): # noqa
class LatexFailed(IOError):
"""Exception for failed latex run
Captured latex output is in error.output.
Expand All @@ -33,8 +33,7 @@ def __unicode__(self):

def __str__(self):
"""String representation."""
u = self.__unicode__()
return u
return self.__unicode__()


def prepend_to_env_search_path(varname, value, envdict):
Expand Down Expand Up @@ -85,9 +84,7 @@ def _file_extension_default(self):
def _template_extension_default(self):
return ".tex.j2"

def run_command( # noqa
self, command_list, filename, count, log_function, raise_on_failure=None
):
def run_command(self, command_list, filename, count, log_function, raise_on_failure=None):
"""Run command_list count times.
Parameters
Expand Down Expand Up @@ -141,12 +138,12 @@ def run_command( # noqa
stdout=stdout,
stderr=subprocess.STDOUT,
stdin=null,
shell=shell, # noqa
shell=shell, # noqa: S603
env=env,
)
out, _ = p.communicate()
if p.returncode:
if self.verbose: # noqa
if self.verbose: # noqa: SIM108
# verbose means I didn't capture stdout with PIPE,
# so it's already been displayed and `out` is None.
out_str = ""
Expand Down
8 changes: 4 additions & 4 deletions nbconvert/exporters/qt_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class QtExporter(HTMLExporter):
"""A qt exporter."""

paginate = None
format = "" # noqa
format = ""

@default("file_extension")
def _file_extension_default(self):
Expand Down Expand Up @@ -41,7 +41,7 @@ def _run_pyqtwebengine(self, html):
with temp_file:
temp_file.write(html.encode("utf-8"))
try:
QtScreenshot = self._check_launch_reqs() # noqa
QtScreenshot = self._check_launch_reqs()
s = QtScreenshot()
s.capture(f"file://{temp_file.name}", filename, self.paginate)
finally:
Expand All @@ -54,9 +54,9 @@ def from_notebook_node(self, nb, resources=None, **kw):
self._check_launch_reqs()
html, resources = super().from_notebook_node(nb, resources=resources, **kw)

self.log.info(f"Building {self.format.upper()}")
self.log.info("Building %s", self.format.upper())
data = self._run_pyqtwebengine(html)
self.log.info(f"{self.format.upper()} successfully created")
self.log.info("%s successfully created", self.format.upper())

# convert output extension
# the writer above required it to be html
Expand Down
2 changes: 1 addition & 1 deletion nbconvert/exporters/qtpdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class QtPDFExporter(QtExporter):
"""

export_from_notebook = "PDF via HTML"
format = "pdf" # noqa
format = "pdf"

paginate = Bool( # type:ignore[assignment]
True,
Expand Down
2 changes: 1 addition & 1 deletion nbconvert/exporters/qtpng.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ class QtPNGExporter(QtExporter):
"""

export_from_notebook = "PNG via HTML"
format = "png" # noqa
format = "png"
2 changes: 1 addition & 1 deletion nbconvert/exporters/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def _get_language_exporter(self, lang_name):
if lang_name not in self._lang_exporters:
try:
exporters = entry_points(group="nbconvert.exporters.script")
exporter = [e for e in exporters if e.name == lang_name][0].load() # noqa
exporter = [e for e in exporters if e.name == lang_name][0].load() # noqa: RUF015
except (KeyError, IndexError):
self._lang_exporters[lang_name] = None
else:
Expand Down
Loading

0 comments on commit a7df9af

Please sign in to comment.