Skip to content

Commit

Permalink
Use ruff format (#992)
Browse files Browse the repository at this point in the history
* use ruff format

* fix type

* fix types
  • Loading branch information
blink1073 authored Oct 29, 2023
1 parent 43d008f commit 586cbb3
Show file tree
Hide file tree
Showing 26 changed files with 216 additions and 256 deletions.
12 changes: 4 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ci:

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-case-conflict
- id: check-ast
Expand Down Expand Up @@ -42,11 +42,6 @@ repos:
- id: blacken-docs
additional_dependencies: [black==23.7.0]

- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.9.1
hooks:
- id: black

- repo: https://github.com/codespell-project/codespell
rev: "v2.2.6"
hooks:
Expand All @@ -61,13 +56,14 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.292
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format

- repo: https://github.com/scientific-python/cookie
rev: "2023.09.21"
rev: "2023.10.27"
hooks:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"]
66 changes: 33 additions & 33 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'myst_parser',
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.napoleon',
'sphinxcontrib_github_alt',
"myst_parser",
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinxcontrib_github_alt",
"sphinx_autodoc_typehints",
]

Expand All @@ -60,23 +60,23 @@ def filter(self, record: pylogging.LogRecord) -> bool:
myst_enable_extensions = ["html_image"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The encoding of source files.
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = 'index'
master_doc = "index"

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

github_project_url = "https://github.com/jupyter/jupyter_client"

Expand All @@ -86,14 +86,14 @@ def filter(self, record: pylogging.LogRecord) -> bool:
#
version_ns: dict = {}
here = os.path.dirname(__file__)
version_py = os.path.join(here, os.pardir, 'jupyter_client', '_version.py')
version_py = os.path.join(here, os.pardir, "jupyter_client", "_version.py")
with open(version_py) as f:
exec(compile(f.read(), version_py, 'exec'), version_ns) # noqa
exec(compile(f.read(), version_py, "exec"), version_ns) # noqa

# The short X.Y version.
version = '%i.%i' % version_ns['version_info'][:2]
version = "%i.%i" % version_ns["version_info"][:2]
# The full version, including alpha/beta/rc tags.
release = version_ns['__version__']
release = version_ns["__version__"]

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -110,7 +110,7 @@ def filter(self, record: pylogging.LogRecord) -> bool:

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]

# The reST default role (used for this markup: `text`) to use for all
# documents.
Expand All @@ -128,7 +128,7 @@ def filter(self, record: pylogging.LogRecord) -> bool:
# show_authors = False

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
Expand All @@ -144,12 +144,12 @@ def filter(self, record: pylogging.LogRecord) -> bool:

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'pydata_sphinx_theme'
html_theme = "pydata_sphinx_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
html_theme_options = {"navigation_with_keys": False}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
Expand Down Expand Up @@ -236,7 +236,7 @@ def filter(self, record: pylogging.LogRecord) -> bool:
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = 'jupyter_clientdoc'
htmlhelp_basename = "jupyter_clientdoc"

# -- Options for LaTeX output ---------------------------------------------

Expand All @@ -257,10 +257,10 @@ def filter(self, record: pylogging.LogRecord) -> bool:
latex_documents = [
(
master_doc,
'jupyter_client.tex',
'jupyter\\_client Documentation',
'Jupyter Development Team',
'manual',
"jupyter_client.tex",
"jupyter\\_client Documentation",
"Jupyter Development Team",
"manual",
),
]

Expand Down Expand Up @@ -289,7 +289,7 @@ def filter(self, record: pylogging.LogRecord) -> bool:

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, 'jupyter_client', 'jupyter_client Documentation', [author], 1)]
man_pages = [(master_doc, "jupyter_client", "jupyter_client Documentation", [author], 1)]

# If true, show URL addresses after external links.
# man_show_urls = False
Expand All @@ -303,12 +303,12 @@ def filter(self, record: pylogging.LogRecord) -> bool:
texinfo_documents = [
(
master_doc,
'jupyter_client',
'jupyter_client Documentation',
"jupyter_client",
"jupyter_client Documentation",
author,
'jupyter_client',
'One line description of project.',
'Miscellaneous',
"jupyter_client",
"One line description of project.",
"Miscellaneous",
),
]

Expand All @@ -326,10 +326,10 @@ def filter(self, record: pylogging.LogRecord) -> bool:


# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'ipython': ('http://ipython.readthedocs.io/en/stable/', None)}
intersphinx_mapping = {"ipython": ("http://ipython.readthedocs.io/en/stable/", None)}


def setup(app: object) -> None:
HERE = osp.abspath(osp.dirname(__file__))
dest = osp.join(HERE, 'changelog.md')
shutil.copy(osp.join(HERE, '..', 'CHANGELOG.md'), dest)
dest = osp.join(HERE, "changelog.md")
shutil.copy(osp.join(HERE, "..", "CHANGELOG.md"), dest)
8 changes: 4 additions & 4 deletions jupyter_client/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
__version__ = "8.5.0"

# Build up version_info tuple for backwards compatibility
pattern = r'(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)'
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
match = re.match(pattern, __version__)
if match:
parts: List[Union[int, str]] = [int(match[part]) for part in ['major', 'minor', 'patch']]
if match['rest']:
parts.append(match['rest'])
parts: List[Union[int, str]] = [int(match[part]) for part in ["major", "minor", "patch"]]
if match["rest"]:
parts.append(match["rest"])
else:
parts = []
version_info = tuple(parts)
Expand Down
2 changes: 1 addition & 1 deletion jupyter_client/channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def __init__(self, socket: zmq.asyncio.Socket, session: Session, loop: t.Any = N
Unused here, for other implementations
"""
if not isinstance(socket, zmq.asyncio.Socket):
msg = 'Socket must be asyncio' # type:ignore[unreachable]
msg = "Socket must be asyncio" # type:ignore[unreachable]
raise ValueError(msg)
super().__init__(socket, session)

Expand Down
4 changes: 1 addition & 3 deletions jupyter_client/consoleapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,7 @@ class JupyterConsoleApp(ConnectionFileMixin):

name: t.Union[str, Unicode] = "jupyter-console-mixin"

description: t.Union[
str, Unicode
] = """
description: t.Union[str, Unicode] = """
The Jupyter Console Mixin.
This class contains the common portions of console client (QtConsole,
Expand Down
12 changes: 6 additions & 6 deletions jupyter_client/jsonutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,10 @@ def json_default(obj: Any) -> Any:
"""default function for packing objects in JSON."""
if isinstance(obj, datetime):
obj = _ensure_tzinfo(obj)
return obj.isoformat().replace('+00:00', 'Z')
return obj.isoformat().replace("+00:00", "Z")

if isinstance(obj, bytes):
return b2a_base64(obj, newline=False).decode('ascii')
return b2a_base64(obj, newline=False).decode("ascii")

if isinstance(obj, Iterable):
return list(obj)
Expand Down Expand Up @@ -157,10 +157,10 @@ def json_clean(obj: Any) -> Any:
if isinstance(obj, bytes):
# unanmbiguous binary data is base64-encoded
# (this probably should have happened upstream)
return b2a_base64(obj, newline=False).decode('ascii')
return b2a_base64(obj, newline=False).decode("ascii")

if isinstance(obj, container_to_list) or (
hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)
hasattr(obj, "__iter__") and hasattr(obj, next_attr_name)
):
obj = list(obj)

Expand All @@ -175,8 +175,8 @@ def json_clean(obj: Any) -> Any:
nkeys_collapsed = len(set(map(str, obj)))
if nkeys != nkeys_collapsed:
msg = (
'dict cannot be safely converted to JSON: '
'key collision would lead to dropped values'
"dict cannot be safely converted to JSON: "
"key collision would lead to dropped values"
)
raise ValueError(msg)
# If all OK, proceed by making the new dict that will be json-safe
Expand Down
4 changes: 2 additions & 2 deletions jupyter_client/kernelspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def _get_kernel_spec_by_name(self, kernel_name: str, resource_dir: str) -> Kerne
pass
else:
if resource_dir == RESOURCES:
kdict = get_kernel_dict() # type:ignore[no-untyped-call]
kdict = get_kernel_dict()
kspec = self.kernel_spec_class(resource_dir=resource_dir, **kdict)
if not kspec:
kspec = self.kernel_spec_class.from_resource_dir(resource_dir)
Expand Down Expand Up @@ -415,7 +415,7 @@ def install_native_kernel_spec(self, user: bool = False) -> None:
)
from ipykernel.kernelspec import install

install(self, user=user) # type:ignore[no-untyped-call]
install(self, user=user)


def find_kernel_specs() -> dict[str, str]:
Expand Down
4 changes: 1 addition & 3 deletions jupyter_client/kernelspecapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,9 +266,7 @@ def start(self) -> None: # pragma: no cover
print("ipykernel not available, can't install its spec.", file=sys.stderr)
self.exit(1)
try:
kernelspec.install(
self.kernel_spec_manager, user=self.user
) # type:ignore[no-untyped-call]
kernelspec.install(self.kernel_spec_manager, user=self.user)
except OSError as e:
if e.errno == errno.EACCES:
print(e, file=sys.stderr)
Expand Down
52 changes: 15 additions & 37 deletions jupyter_client/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ class _ShutdownStatus(Enum):
SigkillRequest = "SigkillRequest"


F = t.TypeVar('F', bound=t.Callable[..., t.Any])
F = t.TypeVar("F", bound=t.Callable[..., t.Any])


def _get_future() -> t.Union[Future, CFuture]:
Expand Down Expand Up @@ -281,7 +281,7 @@ def update_env(self, *, env: t.Dict[str, str]) -> None:
.. version-added: 8.5
"""
self._launch_args['env'].update(env)
self._launch_args["env"].update(env)

def format_kernel_cmd(self, extra_arguments: t.Optional[t.List[str]] = None) -> t.List[str]:
"""Replace templated args (e.g. {connection_file})"""
Expand Down Expand Up @@ -369,7 +369,7 @@ async def _async_pre_start_kernel(
and launching the kernel (e.g. Popen kwargs).
"""
self.shutting_down = False
self.kernel_id = self.kernel_id or kw.pop('kernel_id', str(uuid.uuid4()))
self.kernel_id = self.kernel_id or kw.pop("kernel_id", str(uuid.uuid4()))
# save kwargs for use in restart
self._launch_args = kw.copy()
if self.provisioner is None: # will not be None on restarts
Expand All @@ -379,7 +379,7 @@ async def _async_pre_start_kernel(
parent=self,
)
kw = await self.provisioner.pre_launch(**kw)
kernel_cmd = kw.pop('cmd')
kernel_cmd = kw.pop("cmd")
return kernel_cmd, kw

pre_start_kernel = run_sync(_async_pre_start_kernel)
Expand Down Expand Up @@ -715,41 +715,19 @@ def client( # type:ignore[override]
return super().client(**kwargs) # type:ignore[return-value]

_launch_kernel = KernelManager._async_launch_kernel # type:ignore[assignment]
start_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_start_kernel # type:ignore[assignment]
pre_start_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_pre_start_kernel # type:ignore[assignment]
post_start_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_post_start_kernel # type:ignore[assignment]
request_shutdown: t.Callable[
..., t.Awaitable
] = KernelManager._async_request_shutdown # type:ignore[assignment]
finish_shutdown: t.Callable[
..., t.Awaitable
] = KernelManager._async_finish_shutdown # type:ignore[assignment]
cleanup_resources: t.Callable[
..., t.Awaitable
] = KernelManager._async_cleanup_resources # type:ignore[assignment]
shutdown_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_shutdown_kernel # type:ignore[assignment]
restart_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_restart_kernel # type:ignore[assignment]
start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_start_kernel # type:ignore[assignment]
pre_start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_pre_start_kernel # type:ignore[assignment]
post_start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_post_start_kernel # type:ignore[assignment]
request_shutdown: t.Callable[..., t.Awaitable] = KernelManager._async_request_shutdown # type:ignore[assignment]
finish_shutdown: t.Callable[..., t.Awaitable] = KernelManager._async_finish_shutdown # type:ignore[assignment]
cleanup_resources: t.Callable[..., t.Awaitable] = KernelManager._async_cleanup_resources # type:ignore[assignment]
shutdown_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_shutdown_kernel # type:ignore[assignment]
restart_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_restart_kernel # type:ignore[assignment]
_send_kernel_sigterm = KernelManager._async_send_kernel_sigterm # type:ignore[assignment]
_kill_kernel = KernelManager._async_kill_kernel # type:ignore[assignment]
interrupt_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_interrupt_kernel # type:ignore[assignment]
signal_kernel: t.Callable[
..., t.Awaitable
] = KernelManager._async_signal_kernel # type:ignore[assignment]
is_alive: t.Callable[
..., t.Awaitable
] = KernelManager._async_is_alive # type:ignore[assignment]
interrupt_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_interrupt_kernel # type:ignore[assignment]
signal_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_signal_kernel # type:ignore[assignment]
is_alive: t.Callable[..., t.Awaitable] = KernelManager._async_is_alive # type:ignore[assignment]


KernelManagerABC.register(KernelManager)
Expand Down
Loading

0 comments on commit 586cbb3

Please sign in to comment.