Skip to content

Commit

Permalink
Update ruff and typings (#388)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Dec 5, 2023
1 parent 0708dd6 commit 30d93a2
Show file tree
Hide file tree
Showing 70 changed files with 302 additions and 234 deletions.
10 changes: 5 additions & 5 deletions .github/scripts/create_npmrc.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
#!/usr/bin/env python

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

# Standard library imports
import os
from __future__ import annotations

from pathlib import Path


def create_npmrc():
"""
Create NPM configuration file in user home directory to use authentication
token from environment variables.
"""
fpath = os.path.expanduser("~/.npmrc")
with open(fpath, "w") as fh:
fpath = Path("~/.npmrc").expanduser()
with fpath.open("w") as fh:
fh.write("//registry.npmjs.org/:_authToken=${NPM_TOKEN}")


Expand Down
14 changes: 8 additions & 6 deletions .github/scripts/parse_ref.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
#!/usr/bin/env python

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

# Standard library imports
from __future__ import annotations

import os
from pathlib import Path

# Constants
HERE = os.path.abspath(os.path.dirname(__file__))
REPO_ROOT = os.path.dirname(os.path.dirname(HERE))
HERE = Path(__file__).parent.resolve()
REPO_ROOT = HERE.parent.parent


def parse_ref(current_ref):
Expand All @@ -22,10 +23,11 @@ def parse_ref(current_ref):
The github reference string.
"""
if not current_ref.startswith("refs/tags/"):
raise Exception(f"Invalid ref `{current_ref}`!") # noqa
msg = f"Invalid ref `{current_ref}`!"
raise Exception(msg)

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


if __name__ == "__main__":
Expand Down
8 changes: 4 additions & 4 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.1
rev: 0.27.2
hooks:
- id: check-github-workflows

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

- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v1.6.1"
rev: "v1.7.1"
hooks:
- id: mypy
files: "^nbformat"
Expand All @@ -65,7 +65,7 @@ repos:
["jsonschema>=2.6", "traitlets>=5.13", "jupyter_core>5.4"]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.5
rev: v0.1.6
hooks:
- id: ruff
types_or: [python, jupyter]
Expand All @@ -76,7 +76,7 @@ repos:
types_or: [python, jupyter]

- repo: https://github.com/scientific-python/cookie
rev: "2023.10.27"
rev: "2023.11.17"
hooks:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"]
15 changes: 7 additions & 8 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python3
#
# nbformat documentation build configuration file, created by
# sphinx-quickstart on Thu May 14 17:26:52 2015.
#
Expand All @@ -16,13 +14,14 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
from __future__ import annotations

import os
import shutil
from pathlib import Path

import nbformat

HERE = os.path.abspath(os.path.dirname(__file__))
HERE = Path(__file__).parent.resolve()

# -- General configuration ------------------------------------------------

Expand All @@ -40,7 +39,7 @@
]

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

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

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

# numpydoc configuration
Expand Down Expand Up @@ -313,5 +312,5 @@


def setup(_):
dest = os.path.join(HERE, "changelog.md")
shutil.copy(os.path.join(HERE, "..", "CHANGELOG.md"), dest)
dest = Path(HERE, "changelog.md")
shutil.copy(Path(HERE, "..", "CHANGELOG.md"), dest)
19 changes: 11 additions & 8 deletions nbformat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations

from pathlib import Path

from traitlets.log import get_logger

Expand Down Expand Up @@ -39,12 +42,12 @@
4: v4,
}

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
from . import reader # noqa: E402
from .converter import convert # noqa: E402
from .notebooknode import NotebookNode, from_dict # noqa: E402
from .v4 import nbformat as current_nbformat # noqa: E402
from .v4 import nbformat_minor as current_nbformat_minor # noqa: E402
from .validator import ValidationError, validate # noqa: E402


class NBFormatError(ValueError):
Expand Down Expand Up @@ -165,7 +168,7 @@ def read(fp, as_version, capture_validation_error=None, **kwargs):
try:
buf = fp.read()
except AttributeError:
with open(fp, encoding="utf-8") as f:
with open(fp, encoding="utf8") as f: # noqa: PTH123
return reads(f.read(), as_version, capture_validation_error, **kwargs)

return reads(buf, as_version, capture_validation_error, **kwargs)
Expand Down Expand Up @@ -202,7 +205,7 @@ def write(nb, fp, version=NO_CONVERT, capture_validation_error=None, **kwargs):
if not s.endswith("\n"):
fp.write("\n")
except AttributeError:
with open(fp, "w", encoding="utf-8") as f:
with Path(fp).open("w", encoding="utf8") as f:
f.write(s)
if not s.endswith("\n"):
f.write("\n")
8 changes: 4 additions & 4 deletions nbformat/_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations


def import_item(name):
Expand All @@ -26,7 +27,7 @@ def import_item(name):
"""

parts = name.rsplit(".", 1)
if len(parts) == 2: # noqa
if len(parts) == 2:
# called with 'foo.bar....'
package, obj = parts
module = __import__(package, fromlist=[obj])
Expand All @@ -35,6 +36,5 @@ def import_item(name):
except AttributeError:
raise ImportError("No module named %s" % obj) from None
return pak
else:
# called with un-dotted string
return __import__(parts[0])
# called with un-dotted string
return __import__(parts[0])
20 changes: 11 additions & 9 deletions nbformat/_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Can probably be replaced by types.SimpleNamespace from Python 3.3
"""
from __future__ import annotations

from typing import Any, Dict

__all__ = ["Struct"]
Expand Down Expand Up @@ -88,7 +90,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): # noqa
if isinstance(key, str): # noqa: SIM102
# 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 @@ -196,12 +198,12 @@ def __dict_invert(self, data):
outdict = {}
for k, lst in data.items():
if isinstance(lst, str):
lst = lst.split() # noqa
lst = lst.split() # noqa: PLW2901
for entry in lst:
outdict[entry] = k
return outdict

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

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

def hasattr(self, key): # noqa
def hasattr(self, key):
"""hasattr function available as a method.
Implemented like has_key.
Expand Down Expand Up @@ -331,11 +333,11 @@ def merge(self, __loc_data__=None, __conflict_solve=None, **kw):

# policies for conflict resolution: two argument functions which return
# the value that will go in the new struct
preserve = lambda old, new: old # noqa
update = lambda old, new: new # noqa
add = lambda old, new: old + new # noqa
add_flip = lambda old, new: new + old # noqa # note change of order!
add_s = lambda old, new: old + " " + new # noqa
preserve = lambda old, new: old
update = lambda old, new: new
add = lambda old, new: old + new
add_flip = lambda old, new: new + old # note change of order!
add_s = lambda old, new: old + " " + new

# default policy is to keep current keys when there's a conflict
conflict_solve = dict.fromkeys(self, preserve)
Expand Down
2 changes: 2 additions & 0 deletions nbformat/_version.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""The version information for nbformat."""
# Use "hatchling version xx.yy.zz" to handle version changes
from __future__ import annotations

import re
from importlib.metadata import version

Expand Down
10 changes: 5 additions & 5 deletions nbformat/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations

from . import versions
from .reader import get_version
Expand Down Expand Up @@ -40,7 +41,7 @@ def convert(nb, to_version):
return nb

# If the version exist, try to convert to it one step at a time.
elif to_version in versions:
if to_version in versions:
# Get the the version that this recursion will convert to as a step
# closer to the final revision. Make sure the newer of the conversion
# functions is used to perform the conversion.
Expand All @@ -63,7 +64,6 @@ def convert(nb, to_version):

# Recursively convert until target version is reached.
return convert(converted, to_version)
else:
raise ValueError(
"Cannot convert notebook to v%d because that version doesn't exist" % (to_version)
)
raise ValueError(
"Cannot convert notebook to v%d because that version doesn't exist" % (to_version)
)
7 changes: 4 additions & 3 deletions nbformat/corpus/tests/test_words.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations

from nbformat.corpus import words


def test_generate_corpus_id(recwarn):
"""Test generating a corpus id."""
assert len(words.generate_corpus_id()) > 7 # noqa
assert len(words.generate_corpus_id()) > 7
# 1 in 4294967296 (2^32) times this will fail
assert words.generate_corpus_id() != words.generate_corpus_id() # noqa
assert len(recwarn) == 0 # noqa
assert words.generate_corpus_id() != words.generate_corpus_id()
assert len(recwarn) == 0
2 changes: 2 additions & 0 deletions nbformat/corpus/words.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Generate a corpus id."""
from __future__ import annotations

import uuid


Expand Down
12 changes: 5 additions & 7 deletions nbformat/current.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.

from __future__ import annotations

import re
import warnings
Expand Down Expand Up @@ -83,8 +83,6 @@
class NBFormatError(ValueError):
"""An error raised for an nbformat error."""

pass


def _warn_format():
warnings.warn(
Expand Down Expand Up @@ -150,7 +148,7 @@ def writes_py(nb, **kwargs):
# High level API


def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs):
"""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 @@ -179,7 +177,7 @@ def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
return nb


def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs):
"""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 @@ -209,7 +207,7 @@ def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs): # noqa
return versions[version].writes_json(nb, **kwargs)


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


def write(nb, fp, format="DEPRECATED", **kwargs): # noqa
def write(nb, fp, format="DEPRECATED", **kwargs):
"""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
1 change: 1 addition & 0 deletions nbformat/json_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import annotations

import os

Expand Down
Loading

0 comments on commit 30d93a2

Please sign in to comment.