From 905baff2a1698ac1456580a96930f88b140f40db Mon Sep 17 00:00:00 2001 From: Koncopd Date: Sun, 4 Feb 2024 15:50:19 +0100 Subject: [PATCH] use nbformat for write_notebook --- nbproject/dev/_notebook.py | 14 +++++++------- pyproject.toml | 1 + 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/nbproject/dev/_notebook.py b/nbproject/dev/_notebook.py index b3b5390..a0488f8 100644 --- a/nbproject/dev/_notebook.py +++ b/nbproject/dev/_notebook.py @@ -1,6 +1,7 @@ from pathlib import Path from typing import Union +import nbformat import orjson from pydantic import BaseModel @@ -25,10 +26,11 @@ def read_notebook(filepath: Union[str, Path]) -> Notebook: nb = orjson.loads(f.read()) except orjson.JSONDecodeError as e: if "Input is a zero-length, empty document" in str(e): - raise ValueError("Notebook cannot be empty. It must have at least a title cell.") + raise ValueError( + "Notebook cannot be empty. It must have at least a title cell." + ) from e else: - raise - + raise e return Notebook(**nb) @@ -40,7 +42,5 @@ def write_notebook(nb: Notebook, filepath: Union[str, Path]): nb: Notebook to write. filepath: Path where to write the notebook. """ - with open(filepath, "wb") as f: - # the formatting orjson dumps doesn't match jupyter lab - # maybe one can homogenize it at some point - f.write(orjson.dumps(nb.dict(), option=orjson.OPT_INDENT_2)) + nb_node = nbformat.from_dict(nb.dict()) + nbformat.write(nb_node, filepath, version=nbformat.NO_CONVERT) diff --git a/pyproject.toml b/pyproject.toml index 5f315f2..e0dcfda 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,6 +19,7 @@ dependencies = [ "pyyaml", "packaging", "orjson", + "nbformat", "ipylab", "importlib-metadata", "stdlib_list; python_version < '3.10'",