Skip to content

Commit

Permalink
Add more linting (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Jan 29, 2023
1 parent 5fc0e8d commit 437edb3
Show file tree
Hide file tree
Showing 41 changed files with 265 additions and 275 deletions.
4 changes: 2 additions & 2 deletions .github/scripts/parse_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ def parse_ref(current_ref):
The github reference string.
"""
if not current_ref.startswith("refs/tags/"):
raise Exception(f"Invalid ref `{current_ref}`!")
raise Exception(f"Invalid ref `{current_ref}`!") # noqa

tag_name = current_ref.replace("refs/tags/", "")
print(tag_name)
print(tag_name) # noqa


if __name__ == "__main__":
Expand Down
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.207
rev: v0.0.237
hooks:
- id: ruff
args: ["--fix"]
Expand Down
5 changes: 2 additions & 3 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import os
import shutil
from importlib.metadata import version as get_version

HERE = os.path.abspath(os.path.dirname(__file__))

Expand Down Expand Up @@ -60,7 +61,7 @@

# General information about the project.
project = "nbformat"
copyright = "2015, Jupyter Development Team"
copyright = "2015, Jupyter Development Team" # noqa
author = "Jupyter Development Team"

# numpydoc configuration
Expand All @@ -72,8 +73,6 @@
# built documents.
#
# The short X.Y version.
from importlib.metadata import version as get_version

version = ".".join(get_version("nbformat").split(".")[:2])
# The full version, including alpha/beta/rc tags.
release = version
Expand Down
12 changes: 6 additions & 6 deletions nbformat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@
4: v4,
}

from . import reader
from .converter import convert
from .notebooknode import NotebookNode, from_dict
from .v4 import nbformat as current_nbformat
from .v4 import nbformat_minor as current_nbformat_minor
from .validator import ValidationError, validate
from . import reader # noqa
from .converter import convert # noqa
from .notebooknode import NotebookNode, from_dict # noqa
from .v4 import nbformat as current_nbformat # noqa
from .v4 import nbformat_minor as current_nbformat_minor # noqa
from .validator import ValidationError, validate # noqa


class NBFormatError(ValueError):
Expand Down
2 changes: 1 addition & 1 deletion nbformat/_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def import_item(name):
"""

parts = name.rsplit(".", 1)
if len(parts) == 2:
if len(parts) == 2: # noqa
# called with 'foo.bar....'
package, obj = parts
module = __import__(package, fromlist=[obj])
Expand Down
10 changes: 5 additions & 5 deletions nbformat/_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def __setattr__(self, key, value):
you can't set a class member
"""
# If key is an str it might be a class member or instance var
if isinstance(key, str):
if isinstance(key, str): # noqa
# I can't simply call hasattr here because it calls getattr, which
# calls self.__getattr__, which returns True for keys in
# self._data. But I only want keys in the class and in
Expand Down Expand Up @@ -181,7 +181,7 @@ def __isub__(self, other):
>>> s1
{'b': 30}
"""
for k in other.keys():
for k in other:
if k in self:
del self[k]
return self
Expand All @@ -200,7 +200,7 @@ def __dict_invert(self, data):
outdict[entry] = k
return outdict

def dict(self):
def dict(self): # noqa
"""Get the dict representation of the struct."""
return self

Expand All @@ -216,7 +216,7 @@ def copy(self):
"""
return Struct(dict.copy(self))

def hasattr(self, key):
def hasattr(self, key): # noqa
"""hasattr function available as a method.
Implemented like has_key.
Expand Down Expand Up @@ -352,7 +352,7 @@ def merge(self, __loc_data__=None, __conflict_solve=None, **kw):
("add_flip", add_flip),
("add_s", add_s),
]:
if name in inv_conflict_solve_user.keys():
if name in inv_conflict_solve_user:
inv_conflict_solve_user[func] = inv_conflict_solve_user[name]
del inv_conflict_solve_user[name]
conflict_solve.update(self.__dict_invert(inv_conflict_solve_user))
Expand Down
10 changes: 4 additions & 6 deletions nbformat/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,11 @@ def convert(nb, to_version):
# Convert and make sure version changed during conversion.
converted = convert_function(nb)
if converted.get("nbformat", 1) == version:
raise ValueError(
"Failed to convert notebook from v%d to v%d." % (version, step_version)
)
msg = "Failed to convert notebook from v%d to v%d." % (version, step_version)
raise ValueError(msg)
except AttributeError as e:
raise ValidationError(
f"Notebook could not be converted from version {version} to version {step_version} because it's missing a key: {e}"
) from None
msg = f"Notebook could not be converted from version {version} to version {step_version} because it's missing a key: {e}"
raise ValidationError(msg) from None

# Recursively convert until target version is reached.
return convert(converted, to_version)
Expand Down
8 changes: 4 additions & 4 deletions nbformat/corpus/tests/test_words.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

from .. import words
from nbformat.corpus import words


def test_generate_corpus_id(recwarn):
"""Test generating a corpus id."""
assert len(words.generate_corpus_id()) > 7
assert len(words.generate_corpus_id()) > 7 # noqa
# 1 in 4294967296 (2^32) times this will fail
assert words.generate_corpus_id() != words.generate_corpus_id()
assert len(recwarn) == 0
assert words.generate_corpus_id() != words.generate_corpus_id() # noqa
assert len(recwarn) == 0 # noqa
26 changes: 13 additions & 13 deletions nbformat/current.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,6 @@
import re
import warnings

warnings.warn(
"""nbformat.current is deprecated since before nbformat 3.0
- use nbformat for read/write/validate public API
- use nbformat.vX directly to composing notebooks of a particular version
""",
DeprecationWarning,
)

from traitlets.log import get_logger

from nbformat import v3 as _v_latest
Expand All @@ -45,6 +36,15 @@
from .reader import reads as reader_reads
from .validator import ValidationError, validate

warnings.warn(
"""nbformat.current is deprecated since before nbformat 3.0
- use nbformat for read/write/validate public API
- use nbformat.vX directly to composing notebooks of a particular version
""",
DeprecationWarning,
)

__all__ = [
"NotebookNode",
"new_code_cell",
Expand Down Expand Up @@ -148,7 +148,7 @@ def writes_py(nb, **kwargs):
# High level API


def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs):
def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
"""Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
Expand Down Expand Up @@ -177,7 +177,7 @@ def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs):
return nb


def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs):
def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
"""Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Expand Down Expand Up @@ -207,7 +207,7 @@ def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs):
return versions[version].writes_json(nb, **kwargs)


def read(fp, format="DEPRECATED", **kwargs):
def read(fp, format="DEPRECATED", **kwargs): # noqa
"""Read a notebook from a file and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
Expand All @@ -226,7 +226,7 @@ def read(fp, format="DEPRECATED", **kwargs):
return reads(fp.read(), **kwargs)


def write(nb, fp, format="DEPRECATED", **kwargs):
def write(nb, fp, format="DEPRECATED", **kwargs): # noqa
"""Write a notebook to a file in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Expand Down
11 changes: 6 additions & 5 deletions nbformat/json_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ def error_tree(self, errors):
# Another way forward for compatibility: we could distill both validator errors into a custom collection
# for this data. Since implementation details of ValidationError is used elsewhere, we would probably
# just use this data for schema introspection.
raise NotImplementedError("JSON schema error introspection not enabled for fastjsonschema")
msg = "JSON schema error introspection not enabled for fastjsonschema"
raise NotImplementedError(msg)


_VALIDATOR_MAP = [
Expand All @@ -93,15 +94,15 @@ def error_tree(self, errors):

def _validator_for_name(validator_name):
if validator_name not in VALIDATORS:
raise ValueError(
f"Invalid validator '{validator_name}' value!\nValid values are: {VALIDATORS}"
)
msg = f"Invalid validator '{validator_name}' value!\nValid values are: {VALIDATORS}"
raise ValueError(msg)

for (name, module, validator_cls) in _VALIDATOR_MAP:
if module and validator_name == name:
return validator_cls
# we always return something.
raise ValueError(f"Missing validator for {repr(validator_name)}")
msg = f"Missing validator for {repr(validator_name)}"
raise ValueError(msg)


def get_current_validator():
Expand Down
2 changes: 1 addition & 1 deletion nbformat/notebooknode.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def update(self, *args, **kwargs):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
for key in other:
self[key] = other[key]
else:
for key, value in other:
Expand Down
7 changes: 3 additions & 4 deletions nbformat/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def parse_json(s, **kwargs):
except ValueError as e:
message = f"Notebook does not appear to be JSON: {s!r}"
# Limit the error message to 80 characters. Display whatever JSON will fit.
if len(message) > 80:
if len(message) > 80: # noqa
message = message[:77] + "..."
raise NotJSONError(message) from e
return nb_dict
Expand Down Expand Up @@ -79,9 +79,8 @@ def reads(s, **kwargs):
try:
return versions[major].to_notebook_json(nb_dict, minor=minor)
except AttributeError as e:
raise ValidationError(
f"The notebook is invalid and is missing an expected key: {e}"
) from None
msg = f"The notebook is invalid and is missing an expected key: {e}"
raise ValidationError(msg) from None
else:
raise NBFormatError("Unsupported nbformat version %s" % major)

Expand Down
Loading

0 comments on commit 437edb3

Please sign in to comment.