Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement: add --sort option to marimo export ipynb (#2962)

Myles Scolnick78c7b42d0e8e
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
index 6117b3a13e..7a2a01912d 100644
--- a/marimo/_cli/export/commands.py
+++ b/marimo/_cli/export/commands.py
@@ -2,13 +2,13 @@
from __future__ import annotations
import asyncio
-import importlib.util
-from typing import TYPE_CHECKING, Callable
+from typing import TYPE_CHECKING, Callable, Literal
import click
from marimo._cli.parse_args import parse_args
from marimo._cli.print import echo, green
+from marimo._dependencies.dependencies import DependencyManager
from marimo._server.export import (
export_as_ipynb,
export_as_md,
@@ -267,6 +267,13 @@ Watch for changes and regenerate the script on modification:
Requires nbformat to be installed.
"""
)
+ "--sort",
+ type=click.Choice(["top-down", "topological"]),
+ default="topological",
+ help="Sort cells top-down or in topological order.",
+ show_default=True,
+)
@click.option(
"--watch/--no-watch",
default=False,
@@ -293,18 +300,19 @@ def ipynb(
name: str,
output: str,
watch: bool,
+ sort: Literal["top-down", "topological"],
) -> None:
"""
Export a marimo notebook as a Jupyter notebook in topological order.
"""
def export_callback(file_path: MarimoPath) -> str:
- return export_as_ipynb(file_path)[0]
+ return export_as_ipynb(file_path, sort_mode=sort)[0]
+
+ DependencyManager.nbformat.require(
+ why="to convert marimo notebooks to ipynb"
+ )
- if importlib.util.find_spec("nbformat") is None:
- raise ModuleNotFoundError(
- "Install `nbformat` from PyPI to use marimo export ipynb"
- )
return watch_and_export(MarimoPath(name), output, watch, export_callback)
diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.py
index fe53461330..808a7ded49 100644
--- a/marimo/_dependencies/dependencies.py
+++ b/marimo/_dependencies/dependencies.py
@@ -52,9 +52,9 @@ class Dependency:
"""
if not self.has():
- raise ModuleNotFoundError(
- f"{self.pkg} is required {why}."
- ) from None
+ message = f"{self.pkg} is required {why}."
+ sys.stderr.write(message + "\n\n")
+ raise ModuleNotFoundError(message) from None
def require_at_version(
self,
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 2519bcaa8d..538d566c3f 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -2,7 +2,7 @@
from __future__ import annotations
import asyncio
-from typing import Callable
+from typing import Callable, Literal
from marimo._config.manager import UserConfigManager
from marimo._messaging.ops import MessageOperation
@@ -42,13 +42,14 @@ def export_as_md(
def export_as_ipynb(
path: MarimoPath,
+ sort_mode: Literal["top-down", "topological"],
) -> tuple[str, str]:
file_router = AppFileRouter.from_filename(path)
file_key = file_router.get_unique_file_key()
assert file_key is not None
file_manager = file_router.get_file_manager(file_key)
- return Exporter().export_as_ipynb(file_manager)
+ return Exporter().export_as_ipynb(file_manager, sort_mode=sort_mode)
async def run_app_then_export_as_html(
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index e3847f07b7..3a4760e71a 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -5,7 +5,7 @@ import base64
import io
import mimetypes
import os
-from typing import Optional, cast
+from typing import Literal, Optional, cast
from marimo import __version__
from marimo._ast.cell import Cell, CellConfig, CellImpl
@@ -14,6 +14,7 @@ from marimo._config.config import (
DisplayConfig,
_deep_copy,
)
+from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.utils import build_data_url
from marimo._runtime import dataflow
@@ -133,13 +134,17 @@ class Exporter:
]
code = f'\n__generated_with = "{__version__}"\n\n' + "\n\n".join(codes)
- download_filename = get_download_filename(file_manager, ".script.py")
+ download_filename = get_download_filename(file_manager, "script.py")
return code, download_filename
def export_as_ipynb(
self,
file_manager: AppFileManager,
+ sort_mode: Literal["top-down", "topological"],
) -> tuple[str, str]:
+ DependencyManager.nbformat.require(
+ "to convert marimo notebooks to ipynb"
+ )
import nbformat # type: ignore
def create_notebook_cell(cell: CellImpl) -> nbformat.NotebookNode:
@@ -155,15 +160,23 @@ class Exporter:
notebook = nbformat.v4.new_notebook() # type: ignore
graph = file_manager.app.graph
+
+ if sort_mode == "top-down":
+ # Get cells in document order
+ cell_ids = list(file_manager.app.cell_manager.cell_ids())
+ else:
+ # Get cells in topological order
+ cell_ids = dataflow.topological_sort(graph, graph.cells.keys())
+
notebook["cells"] = [
create_notebook_cell(graph.cells[cid]) # type: ignore
- for cid in dataflow.topological_sort(graph, graph.cells.keys())
+ for cid in cell_ids
]
stream = io.StringIO()
nbformat.write(notebook, stream) # type: ignore
stream.seek(0)
- download_filename = get_download_filename(file_manager, ".ipynb")
+ download_filename = get_download_filename(file_manager, "ipynb")
return stream.read(), download_filename
def export_as_md(self, file_manager: AppFileManager) -> tuple[str, str]:
@@ -260,7 +273,7 @@ class Exporter:
previous_was_markdown = False
document.append(formatted_code_block(code, attributes))
- download_filename = get_download_filename(file_manager, ".md")
+ download_filename = get_download_filename(file_manager, "md")
return "\n".join(document).strip(), download_filename
diff --git a/tests/_cli/snapshots/ipynb.txt b/tests/_cli/snapshots/ipynb.txt
index 0d8950a996..7b5c438161 100644
--- a/tests/_cli/snapshots/ipynb.txt
+++ b/tests/_cli/snapshots/ipynb.txt
@@ -3,17 +3,25 @@
{
"cell_type": "code",
"execution_count": null,
- "id": "Hbol",
+ "id": "bkHC",
"metadata": {},
"outputs": [],
"source": [
"import marimo as mo"
]
},
+ {
+ "cell_type": "markdown",
+ "id": "vblA",
+ "metadata": {},
+ "source": [
+ "plain markdown"
+ ]
+ },
{
"cell_type": "code",
"execution_count": null,
- "id": "MJUe",
+ "id": "Hbol",
"metadata": {},
"outputs": [],
"source": [
@@ -24,7 +32,7 @@
{
"cell_type": "code",
"execution_count": null,
- "id": "vblA",
+ "id": "MJUe",
"metadata": {},
"outputs": [],
"source": [
diff --git a/tests/_cli/snapshots/ipynb_topdown.txt b/tests/_cli/snapshots/ipynb_topdown.txt
new file mode 100644
index 0000000000..40168689a3
--- /dev/null
+++ b/tests/_cli/snapshots/ipynb_topdown.txt
@@ -0,0 +1,48 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "control_dep = None\n",
+ "mo.md(\"markdown\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "control_dep\n",
+ "mo.md(f\"parametrized markdown {123}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "vblA",
+ "metadata": {},
+ "source": [
+ "plain markdown"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bkHC",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import marimo as mo"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
+
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 80f02dac17..cb88f1ce40 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -455,3 +455,37 @@ class TestExportIpynb:
output = p.stdout.decode()
# ipynb has non-deterministic ids
snapshot("ipynb.txt", output)
+
+ @pytest.mark.skipif(
+ not DependencyManager.nbformat.has(),
+ reason="This test requires nbformat.",
+ )
+ def test_export_ipynb_sort_modes(
+ self, temp_marimo_file_with_md: str
+ ) -> None:
+ # Test topological sort (default)
+ p = subprocess.run(
+ ["marimo", "export", "ipynb", temp_marimo_file_with_md],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ topo_output = p.stdout.decode()
+
+ # Test top-down sort
+ p = subprocess.run(
+ [
+ "marimo",
+ "export",
+ "ipynb",
+ temp_marimo_file_with_md,
+ "--sort",
+ "top-down",
+ ],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ topdown_output = p.stdout.decode()
+ snapshot("ipynb_topdown.txt", topdown_output)
+
+ # Outputs should be different since sorting is different
+ assert topo_output != topdown_output
diff --git a/tests/_server/export/snapshots/empty_notebook.ipynb.txt b/tests/_server/export/snapshots/empty_notebook.ipynb.txt
new file mode 100644
index 0000000000..363fcab7ed
--- /dev/null
+++ b/tests/_server/export/snapshots/empty_notebook.ipynb.txt
@@ -0,0 +1,6 @@
+{
+ "cells": [],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_server/export/snapshots/notebook_top_down.ipynb.txt b/tests/_server/export/snapshots/notebook_top_down.ipynb.txt
new file mode 100644
index 0000000000..f6ad6857cb
--- /dev/null
+++ b/tests/_server/export/snapshots/notebook_top_down.ipynb.txt
@@ -0,0 +1,37 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "z = x + y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = 1"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_server/export/snapshots/notebook_topological.ipynb.txt b/tests/_server/export/snapshots/notebook_topological.ipynb.txt
new file mode 100644
index 0000000000..923d427e42
--- /dev/null
+++ b/tests/_server/export/snapshots/notebook_topological.ipynb.txt
@@ -0,0 +1,37 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "x = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "y = 1"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "z = x + y"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_server/export/snapshots/notebook_with_cells.ipynb.txt b/tests/_server/export/snapshots/notebook_with_cells.ipynb.txt
new file mode 100644
index 0000000000..042c84263b
--- /dev/null
+++ b/tests/_server/export/snapshots/notebook_with_cells.ipynb.txt
@@ -0,0 +1,17 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"hello\")"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
new file mode 100644
index 0000000000..e090ef0795
--- /dev/null
+++ b/tests/_server/export/test_exporter.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._ast.app import App, InternalApp
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._server.export.exporter import Exporter
+from marimo._server.file_manager import AppFileManager
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+HAS_NBFORMAT = DependencyManager.nbformat.has()
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_export_ipynb_empty():
+ app = App()
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ content, filename = exporter.export_as_ipynb(
+ file_manager, sort_mode="top-down"
+ )
+ assert filename == "notebook.ipynb"
+ snapshot("empty_notebook.ipynb.txt", content)
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_export_ipynb_with_cells():
+ app = App()
+
+ @app.cell()
+ def cell_1():
+ print("hello")
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ content, filename = exporter.export_as_ipynb(
+ file_manager, sort_mode="top-down"
+ )
+ assert filename == "notebook.ipynb"
+ snapshot("notebook_with_cells.ipynb.txt", content)
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_export_ipynb_sort_modes():
+ app = App()
+
+ @app.cell()
+ def result(x, y):
+ z = x + y
+ return (z,)
+
+ @app.cell()
+ def __():
+ x = 1
+ return (x,)
+
+ @app.cell()
+ def __():
+ y = 1
+ return (y,)
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ exporter = Exporter()
+
+ # Test top-down mode preserves document order
+ content, _ = exporter.export_as_ipynb(file_manager, sort_mode="top-down")
+ snapshot("notebook_top_down.ipynb.txt", content)
+
+ # Test topological mode respects dependencies
+ content, _ = exporter.export_as_ipynb(
+ file_manager, sort_mode="topological"
+ )
+ snapshot("notebook_topological.ipynb.txt", content)
diff --git a/tests/conftest.py b/tests/conftest.py
index 6ae1eb00a5..15d93d1385 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -306,11 +306,6 @@ def temp_marimo_file_with_md() -> Generator[str, None, None]:
import marimo
app = marimo.App()
- @app.cell
- def __():
- import marimo as mo
- return mo,
-
@app.cell
def __(mo):
control_dep = None
@@ -323,6 +318,15 @@ def temp_marimo_file_with_md() -> Generator[str, None, None]:
mo.md(f"parametrized markdown {123}")
return
+ @app.cell
+ def __():
+ mo.md("plain markdown")
+ return mo,
+
+ @app.cell
+ def __():
+ import marimo as mo
+ return mo,
if __name__ == "__main__":
app.run()