Skip to content

Commit

Permalink
Update myst_nb/core/config.py to new warnings system
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoshanuikabundi committed Jun 8, 2023
1 parent 18b35f3 commit bceccca
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 17 deletions.
41 changes: 24 additions & 17 deletions myst_nb/core/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Configuration for myst-nb."""
from __future__ import annotations

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

from myst_parser.config.dc_validators import (
ValidatorType,
Expand All @@ -14,12 +16,14 @@
)
from typing_extensions import Literal

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 @@ -54,7 +58,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 @@ -126,7 +130,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 @@ -178,7 +182,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 @@ -376,7 +380,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 @@ -448,7 +452,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 @@ -465,7 +469,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 @@ -498,7 +502,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 @@ -538,19 +542,19 @@ 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():
yield name, value, fields[name]

def copy(self, **changes) -> "NbParserConfig":
def copy(self, **changes) -> NbParserConfig:
"""Return a copy of the configuration with optional changes applied."""
return dc.replace(self, **changes)

Expand All @@ -566,8 +570,8 @@ def __getitem__(self, field: str) -> Any:
def get_cell_level_config(
self,
field_name: str,
cell_metadata: Dict[str, Any],
warning_callback: Callable[[str, str], Any],
cell_metadata: dict[str, Any],
warning_callback: Callable[[str, MystNBWarnings], Any],
) -> Any:
"""Get a configuration value at the cell level.
Expand All @@ -593,7 +597,7 @@ def get_cell_level_config(
warning_callback(
f"Deprecated `cell_metadata_key` 'render' "
f"found, replace with {self.cell_metadata_key!r}",
"cell_metadata_key",
MystNBWarnings.CELL_METADATA_KEY,
)
cell_meta = cell_metadata["render"]
else:
Expand All @@ -611,7 +615,10 @@ def get_cell_level_config(
field.metadata["validator"](self, field, value)
return value
except Exception as exc:
warning_callback(f"Cell metadata invalid: {exc}", "cell_config")
warning_callback(
f"Cell metadata invalid: {exc}",
MystNBWarnings.CELL_CONFIG,
)

# default/global/file level should have already been merged
return getattr(self, field.name)
5 changes: 5 additions & 0 deletions myst_nb/warnings_.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ class MystNBWarnings(Enum):
OUTPUT_TYPE = "output_type"
"""Issue resolving Output type"""

CELL_METADATA_KEY = "cell_metadata_key"
"""Issue with a key in a cell's `metadata` dictionary."""
CELL_CONFIG = "cell_config"
"""Issue with a cell's configuration or metadata."""


def _is_suppressed_warning(
type: str, subtype: str, suppress_warnings: Sequence[str]
Expand Down

0 comments on commit bceccca

Please sign in to comment.