Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ repos:
- id: trailing-whitespace

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

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v2.1.0
rev: v2.3.1
hooks:
- id: mypy
args: [--config-file=pyproject.toml]
Expand All @@ -52,7 +52,7 @@ repos:
)$

- repo: https://github.com/codespell-project/codespell
rev: v2.4.2
rev: v2.4.3
hooks:
- id: codespell
args: ["-S", "*.ipynb"]
6 changes: 3 additions & 3 deletions docs/authoring/basics.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ the [source_suffix](https://www.sphinx-doc.org/en/master/usage/configuration.htm
```python
extensions = ["myst_nb"]
source_suffix = {
'.rst': 'restructuredtext',
'.ipynb': 'myst-nb',
'.myst': 'myst-nb',
".rst": "restructuredtext",
".ipynb": "myst-nb",
".myst": "myst-nb",
}
```

Expand Down
2 changes: 1 addition & 1 deletion docs/computation/execute.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ nb_execution_mode = "off"
To exclude certain file patterns from execution, use the following configuration:

```python
nb_execution_excludepatterns = ['list', 'of', '*patterns']
nb_execution_excludepatterns = ["list", "of", "*patterns"]
```

Any file that matches one of the items in `nb_execution_excludepatterns` will not be executed.
Expand Down
5 changes: 1 addition & 4 deletions docs/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ mystnb-quickstart my_project/docs/
or simply add `myst_nb` to your existing Sphinx configuration:

```python
extensions = [
...,
"myst_nb"
]
extensions = [..., "myst_nb"]
```

By default, MyST-NB will now parse both markdown (`.md`) and notebooks (`.ipynb`).
Expand Down
6 changes: 3 additions & 3 deletions docs/render/format_code_cells.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ For example, the following configuration applies in order:

```python
nb_mime_priority_overrides = [
('html', 'text/plain', 0),
('latex', 'image/jpeg', None),
('*', 'customtype', 20)
("html", "text/plain", 0),
("latex", "image/jpeg", None),
("*", "customtype", 20),
]
```

Expand Down
4 changes: 3 additions & 1 deletion docs/render/interactive.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ fig
You may need to supply the `require.js` for plotly to display; in your `conf.py`:

```python
html_js_files = ["https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"]
html_js_files = [
"https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"
]
```

:::
Expand Down
2 changes: 1 addition & 1 deletion docs/render/orphaned_nb.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"data = np.random.rand(3, 100) * 100\n",
"\n",
Expand Down
25 changes: 13 additions & 12 deletions myst_nb/core/config.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Configuration for myst-nb."""

from collections.abc import Callable, Iterable, Sequence
import dataclasses as dc
from enum import Enum
from typing import Any, Callable, Dict, Iterable, Literal, Optional, Sequence, Tuple
from typing import Any, Literal

from myst_parser.config.dc_validators import (
ValidatorType,
Expand All @@ -17,11 +18,11 @@
from myst_nb.warnings_ import MystNBWarnings


def custom_formats_converter(value: dict) -> Dict[str, Tuple[str, dict, bool]]:
def custom_formats_converter(value: dict) -> dict[str, tuple[str, dict, bool]]:
"""Convert the custom format dict."""
if not isinstance(value, dict):
raise TypeError(f"`nb_custom_formats` must be a dict: {value}")
output: Dict[str, Tuple[str, dict, bool]] = {}
output: dict[str, tuple[str, dict, bool]] = {}
for suffix, reader in value.items():
if not isinstance(suffix, str):
raise TypeError(f"`nb_custom_formats` keys must be a string: {suffix}")
Expand Down Expand Up @@ -56,7 +57,7 @@ def custom_formats_converter(value: dict) -> Dict[str, Tuple[str, dict, bool]]:
return output


def ipywidgets_js_factory() -> Dict[str, Dict[str, str]]:
def ipywidgets_js_factory() -> dict[str, dict[str, str]]:
"""Create a default ipywidgets js dict."""
# see: https://ipywidgets.readthedocs.io/en/7.6.5/embedding.html
return {
Expand Down Expand Up @@ -128,7 +129,7 @@ def __post_init__(self):

# file read options

custom_formats: Dict[str, Tuple[str, dict, bool]] = dc.field(
custom_formats: dict[str, tuple[str, dict, bool]] = dc.field(
default_factory=dict,
metadata={
"help": "Custom formats for reading notebook; suffix -> reader",
Expand Down Expand Up @@ -180,7 +181,7 @@ def __post_init__(self):

# notebook execution options

kernel_rgx_aliases: Dict[str, str] = dc.field(
kernel_rgx_aliases: dict[str, str] = dc.field(
default_factory=dict,
metadata={
"validator": deep_mapping(instance_of(str), instance_of(str)),
Expand Down Expand Up @@ -400,7 +401,7 @@ def __post_init__(self):
},
repr=False,
)
mime_priority_overrides: Sequence[Tuple[str, str, Optional[int]]] = dc.field(
mime_priority_overrides: Sequence[tuple[str, str, int | None]] = dc.field(
default=(),
metadata={
"validator": deep_iterable(
Expand Down Expand Up @@ -472,7 +473,7 @@ def __post_init__(self):
),
},
)
render_image_options: Dict[str, str] = dc.field(
render_image_options: dict[str, str] = dc.field(
default_factory=dict,
# see https://docutils.sourceforge.io/docs/ref/rst/directives.html#image
metadata={
Expand All @@ -489,7 +490,7 @@ def __post_init__(self):
),
},
)
render_figure_options: Dict[str, str] = dc.field(
render_figure_options: dict[str, str] = dc.field(
default_factory=dict,
# see https://docutils.sourceforge.io/docs/ref/rst/directives.html#figure
metadata={
Expand Down Expand Up @@ -522,7 +523,7 @@ def __post_init__(self):
# TODO jupyter_sphinx_require_url and jupyter_sphinx_embed_url (undocumented),
# are no longer used by this package, replaced by ipywidgets_js
# do we add any deprecation warnings?
ipywidgets_js: Dict[str, Dict[str, str]] = dc.field(
ipywidgets_js: dict[str, dict[str, str]] = dc.field(
default_factory=ipywidgets_js_factory,
metadata={
"validator": deep_mapping(
Expand Down Expand Up @@ -562,13 +563,13 @@ def __post_init__(self):
)

@classmethod
def get_fields(cls) -> Tuple[dc.Field, ...]:
def get_fields(cls) -> tuple[dc.Field, ...]:
return dc.fields(cls)

def as_dict(self, dict_factory=dict) -> dict:
return dc.asdict(self, dict_factory=dict_factory)

def as_triple(self) -> Iterable[Tuple[str, Any, dc.Field]]:
def as_triple(self) -> Iterable[tuple[str, Any, dc.Field]]:
"""Yield triples of (name, value, field)."""
fields = {f.name: f for f in dc.fields(self.__class__)}
for name, value in dc.asdict(self).items():
Expand Down
2 changes: 1 addition & 1 deletion myst_nb/core/execute/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
from .inline import NotebookClientInline

if TYPE_CHECKING:
from nbformat import NotebookNode
from jupyter_client import KernelManager
from nbformat import NotebookNode

from myst_nb.core.config import NbParserConfig
from myst_nb.core.loggers import LoggerType
Expand Down
2 changes: 1 addition & 1 deletion myst_nb/core/execute/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from pathlib import Path
from typing import Any, TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from nbformat import NotebookNode
from typing_extensions import TypedDict, final
Expand Down
14 changes: 4 additions & 10 deletions myst_nb/core/read.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

from __future__ import annotations

from collections.abc import Callable, Iterator
import dataclasses as dc
from functools import partial
import json
from pathlib import Path
from typing import Callable, Iterator

from docutils.parsers.rst import Directive
from markdown_it.renderer import RendererHTML
Expand Down Expand Up @@ -326,9 +326,7 @@ def _read_fenced_cell(token, cell_index, cell_type):
)
if result.warnings:
raise MystMetadataParsingError(
"{} cell {} at line {} could not be read: {}".format(
cell_type, cell_index, token.map[0] + 1, result.warnings[0]
)
f"{cell_type} cell {cell_index} at line {token.map[0] + 1} could not be read: {result.warnings[0]}"
)

return result.options, result.body
Expand All @@ -341,15 +339,11 @@ def _read_cell_metadata(token, cell_index):
metadata = json.loads(token.content.strip())
except Exception as err:
raise MystMetadataParsingError(
"Markdown cell {} at line {} could not be read: {}".format(
cell_index, token.map[0] + 1, err
)
f"Markdown cell {cell_index} at line {token.map[0] + 1} could not be read: {err}"
)
if not isinstance(metadata, dict):
raise MystMetadataParsingError(
"Markdown cell {} at line {} is not a dict".format(
cell_index, token.map[0] + 1
)
f"Markdown cell {cell_index} at line {token.map[0] + 1} is not a dict"
)

return metadata
Expand Down
5 changes: 3 additions & 2 deletions myst_nb/core/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from __future__ import annotations

from binascii import a2b_base64
from collections.abc import Iterator, Sequence
from contextlib import contextmanager
import dataclasses as dc
from functools import lru_cache
Expand All @@ -16,7 +17,7 @@
import os
from pathlib import Path
import re
from typing import TYPE_CHECKING, Any, ClassVar, Iterator, Sequence, Union
from typing import TYPE_CHECKING, Any, ClassVar, Union

from docutils import nodes
from docutils.parsers.rst import directives as options_spec
Expand Down Expand Up @@ -935,7 +936,7 @@ def strip_latex_delimiters(source):
https://github.com/jupyter/jupyter-sphinx/issues/90 for discussion.
"""
source = source.strip()
delimiter_pairs = (pair.split() for pair in r"\( \),\[ \],$$ $$,$ $".split(","))
delimiter_pairs = (pair.split() for pair in [r"\( \)", r"\[ \]", r"$$ $$", r"$ $"])
for start, end in delimiter_pairs:
if source.startswith(start) and source.endswith(end):
return source[len(start) : -len(end)]
Expand Down
4 changes: 2 additions & 2 deletions myst_nb/docutils_.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from functools import lru_cache, partial
from importlib import resources as import_resources
import os
from typing import Any, TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from docutils import nodes
from docutils.core import default_description, publish_cmdline
Expand Down Expand Up @@ -153,7 +153,7 @@ def _parse(self, inputstring: str, document: nodes.document) -> None:
notebook = nb_reader.read(inputstring)

# update the global markdown config with the file-level config
warning = lambda wtype, msg: create_warning( # noqa: E731
warning = lambda wtype, msg: create_warning(
document, msg, line=1, append_to=document, subtype=wtype
)
nb_reader.md_config = merge_file_level(
Expand Down
8 changes: 5 additions & 3 deletions myst_nb/ext/execution_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

from __future__ import annotations

from collections import defaultdict
from collections.abc import Callable
from datetime import datetime
import posixpath
from typing import Any, Callable, DefaultDict
from typing import Any

from docutils import nodes
from sphinx.addnodes import pending_xref
Expand Down Expand Up @@ -104,7 +106,7 @@ def run(self, **kwargs) -> None:


def make_stat_table(
parent_docname: str, metadata: DefaultDict[str, dict]
parent_docname: str, metadata: defaultdict[str, dict]
) -> nodes.table:
"""Create a table of statistics on executed notebooks."""

Expand Down Expand Up @@ -158,7 +160,7 @@ def make_stat_table(
row.append(nodes.entry("", paragraph))

# other rows
for name in _key2header.keys():
for name in _key2header:
paragraph = nodes.paragraph()
if name == "succeeded" and data[name] is False:
paragraph += nodes.abbreviation(
Expand Down
5 changes: 3 additions & 2 deletions myst_nb/ext/glue/crossref.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@
from __future__ import annotations

from binascii import a2b_base64
from collections.abc import Sequence
from functools import lru_cache
import hashlib
import json
from mimetypes import guess_extension
from pathlib import Path
from typing import Any, Sequence
import os
from pathlib import Path
from typing import Any

from docutils import nodes
from sphinx.builders import Builder
Expand Down
Loading