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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
tests: idempotnent ipynb (#7939)
Myles Scolnicke94fd8709bec
diff --git a/marimo/_convert/common/format.py b/marimo/_convert/common/format.pyindex caa2e6b773..da04ee06a0 100644--- a/marimo/_convert/common/format.py+++ b/marimo/_convert/common/format.py@@ -9,8 +9,12 @@ from marimo._ast.compiler import extract_markdownif TYPE_CHECKING:from marimo._ast.cell import Cell, CellImpl+DEFAULT_MARKDOWN_PREFIX = "r"-def markdown_to_marimo(source: str) -> str:++def markdown_to_marimo(+ source: str, prefix: str = DEFAULT_MARKDOWN_PREFIX+) -> str:# NB. This should be kept in sync with the logic in# frontend/src/core/codemirror/language/languages/markdown.ts# ::transformOut@@ -19,7 +23,7 @@ def markdown_to_marimo(source: str) -> str:# 6 quotes in a row breaksif not source:source = " "- return codegen.construct_markdown_call(source, '"""', "r")+ return codegen.construct_markdown_call(source, '"""', prefix)def sql_to_marimo(diff --git a/marimo/_convert/ipynb/from_ir.py b/marimo/_convert/ipynb/from_ir.pyindex cc2643e454..bc9ee5cdc5 100644--- a/marimo/_convert/ipynb/from_ir.py+++ b/marimo/_convert/ipynb/from_ir.py@@ -32,6 +32,17 @@ if TYPE_CHECKING:# Note: We intentionally omit "version" as it would vary across environments# and break reproducibility. The marimo_version in metadata is sufficient.+_MD_PREFIX_RE = re.compile(r'mo\.md\(([fFrR]*)(?:"""|\'\'\'|"|\')')+++def _extract_markdown_prefix(code: str) -> str:+ """Extract the string prefix from a mo.md() call (e.g. '', 'r', 'f', 'fr')."""+ m = _MD_PREFIX_RE.search(code)+ if m:+ return m.group(1).lower()+ return ""++DEFAULT_LANGUAGE_INFO = {"codemirror_mode": {"name": "ipython", "version": 3},"file_extension": ".py",@@ -162,7 +173,9 @@ def _create_ipynb_cell(nbformat.NotebookNode,nbformat.v4.new_markdown_cell(markdown_string, id=cell_id), # type: ignore[no-untyped-call])- _add_marimo_metadata(node, name, config)+ _add_marimo_metadata(+ node, name, config, md_prefix=_extract_markdown_prefix(code)+ )return nodenode = cast(@@ -176,7 +189,10 @@ def _create_ipynb_cell(def _add_marimo_metadata(- node: NotebookNode, name: str, config: CellConfig+ node: NotebookNode,+ name: str,+ config: CellConfig,+ md_prefix: Optional[str] = None,) -> None:"""Add marimo-specific metadata to a notebook cell."""marimo_metadata: dict[str, Any] = {}@@ -184,6 +200,10 @@ def _add_marimo_metadata(marimo_metadata["config"] = config.asdict_without_defaults()if not is_internal_cell_name(name):marimo_metadata["name"] = name+ if md_prefix is not None:+ # Always store prefix for markdown cells so importer knows the original+ # prefix and can distinguish marimo-created cells from foreign ipynb cells+ marimo_metadata["md_prefix"] = md_prefixif marimo_metadata:node["metadata"]["marimo"] = marimo_metadatadiff --git a/marimo/_convert/ipynb/to_ir.py b/marimo/_convert/ipynb/to_ir.pyindex 6ff7c0c8af..badac93634 100644--- a/marimo/_convert/ipynb/to_ir.py+++ b/marimo/_convert/ipynb/to_ir.py@@ -11,10 +11,14 @@ from typing import Any, Callable, Unionfrom marimo._ast.cell import CellConfigfrom marimo._ast.compiler import compile_cell+from marimo._ast.names import DEFAULT_CELL_NAMEfrom marimo._ast.transformers import NameTransformer, RemoveImportTransformerfrom marimo._ast.variables import is_localfrom marimo._ast.visitor import Block, NamedNode, ScopedVisitor-from marimo._convert.common.format import markdown_to_marimo+from marimo._convert.common.format import (+ DEFAULT_MARKDOWN_PREFIX,+ markdown_to_marimo,+)from marimo._runtime.dataflow import DirectedGraphfrom marimo._schemas.serialization import (AppInstantiation,@@ -31,6 +35,7 @@ Transform = Callable[[list[str]], list[str]]@dataclassclass CodeCell:source: str+ name: str = field(default_factory=lambda: DEFAULT_CELL_NAME)config: CellConfig = field(default_factory=CellConfig)@@ -1169,24 +1174,30 @@ def bind_cell_metadata(cells: list[CodeCell] = []for source, meta, hide_code in zip(sources, metadata, hide_flags):tags: set[str] = set(meta.get("tags", []))- if "hide-cell" in tags:- tags.discard("hide-cell")- hide_code = True- if tags:- source = f"# Cell tags: {', '.join(sorted(tags))}\n{source}"# Extract marimo-specific cell config if presentmarimo_meta = meta.get("marimo", {})marimo_config = marimo_meta.get("config", {})+ name = marimo_meta.get("name", DEFAULT_CELL_NAME)- # Merge marimo config with existing flags- # marimo config takes precedence for hide_code if present+ # Determine hide_code with priority: marimo config > tags > hide_flags defaultif "hide_code" in marimo_config:hide_code = marimo_config["hide_code"]+ elif "hide-cell" in tags:+ tags.discard("hide-cell")+ hide_code = True+ elif "marimo" in meta:+ # Cell was created by marimo; marimo would have stored hide_code=True+ # explicitly if needed, so default to False instead of is_markdown+ hide_code = False++ if tags:+ source = f"# Cell tags: {', '.join(sorted(tags))}\n{source}"cells.append(CodeCell(source=source,+ name=name,config=CellConfig(hide_code=hide_code,column=marimo_config.get("column"),@@ -1393,7 +1404,11 @@ def convert_from_ipynb_to_notebook_ir()is_markdown: bool = cell["cell_type"] == "markdown"if is_markdown:- source = markdown_to_marimo(source)+ cell_meta = cell.get("metadata", {})+ md_prefix = cell_meta.get("marimo", {}).get(+ "md_prefix", DEFAULT_MARKDOWN_PREFIX+ )+ source = markdown_to_marimo(source, prefix=md_prefix)elif inline_meta is None:# Eagerly find PEP 723 metadata, first match winsinline_meta, source = extract_inline_meta(source)@@ -1420,6 +1435,7 @@ def convert_from_ipynb_to_notebook_ir(cells=[CellDef(code=cell.source,+ name=cell.name,options=cell.config.asdict(),)for cell in transformed_cellsdiff --git a/tests/_cli/snapshots/export/ipynb/ipynb.txt b/tests/_cli/snapshots/export/ipynb/ipynb.txtindex 9f7dc7c801..bad666130e 100644--- a/tests/_cli/snapshots/export/ipynb/ipynb.txt+++ b/tests/_cli/snapshots/export/ipynb/ipynb.txt@@ -35,7 +35,11 @@{"cell_type": "markdown","id": "vblA",- "metadata": {},+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },"source": ["plain markdown"]diff --git a/tests/_cli/snapshots/export/ipynb/ipynb_topdown.txt b/tests/_cli/snapshots/export/ipynb/ipynb_topdown.txtindex 06c68b9981..db3acb56fe 100644--- a/tests/_cli/snapshots/export/ipynb/ipynb_topdown.txt+++ b/tests/_cli/snapshots/export/ipynb/ipynb_topdown.txt@@ -25,7 +25,11 @@{"cell_type": "markdown","id": "vblA",- "metadata": {},+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },"source": ["plain markdown"]diff --git a/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt b/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txtindex b218f32d12..70932fa76a 100644--- a/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt+++ b/tests/_cli/snapshots/export/ipynb/ipynb_with_media_outputs.txt@@ -27,6 +27,7 @@"id": "MJUe","metadata": {"marimo": {+ "md_prefix": "","name": "pure_markdown_cell"}},diff --git a/tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txt b/tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txtindex 6ea713a358..379c6300fc 100644--- a/tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txt+++ b/tests/_cli/snapshots/export/ipynb/ipynb_with_outputs.txt@@ -55,7 +55,11 @@{"cell_type": "markdown","id": "vblA",- "metadata": {},+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },"source": ["plain markdown"]diff --git a/tests/_convert/ipynb/fixtures/py/cell_config.py b/tests/_convert/ipynb/fixtures/py/cell_config.pynew file mode 100644index 0000000000..6caf43efb0--- /dev/null+++ b/tests/_convert/ipynb/fixtures/py/cell_config.py@@ -0,0 +1,41 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ import marimo as mo++ return (mo,)+++def _():+ x = 1+ return (x,)++[email protected](hide_code=True)+def _(mo):+ mo.md("""+ # This cell is hidden+ """)+ return++[email protected](disabled=True)+def _(x):+ y = x + 1+ return (y,)+++def _(y):+ print(y)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/ipynb/fixtures/py/cell_names_and_defs.py b/tests/_convert/ipynb/fixtures/py/cell_names_and_defs.pynew file mode 100644index 0000000000..fa47f3f657--- /dev/null+++ b/tests/_convert/ipynb/fixtures/py/cell_names_and_defs.py@@ -0,0 +1,52 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def my_imports():+ import os+ import sys++ return os, sys+++def compute(os, sys):+ result = os.getcwd() + sys.platform+ return (result,)+++def display(result):+ print(result)+ return+++def add(a, b):+ return a + b++[email protected](hide_code=True)+def subtract(a, b):+ return a - b++[email protected]_definition+class MyClass:+ def __init__(self, val):+ self.val = val+ def double(self):+ return self.val * 2++[email protected]_definition(hide_code=True)+class HiddenClass:+ def __init__(self, val):+ self.val = val+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/ipynb/fixtures/py/complex_file_format.py b/tests/_convert/ipynb/fixtures/py/complex_file_format.pyindex 06bec5335f..bee476da49 100644--- a/tests/_convert/ipynb/fixtures/py/complex_file_format.py+++ b/tests/_convert/ipynb/fixtures/py/complex_file_format.py@@ -10,7 +10,7 @@import marimo-__generated_with = "0.19.2"+__generated_with = "0.0.0"app = marimo.App(width="medium", auto_download=["html"], sql_output="native")with app.setup:@@ -36,6 +36,7 @@ def imports():"""Named cell with imports."""import pandas as pdimport numpy as np+return np, pddiff --git a/tests/_convert/ipynb/fixtures/py/complex_outputs.py b/tests/_convert/ipynb/fixtures/py/complex_outputs.pyindex 8819ff26de..081060b5f8 100644--- a/tests/_convert/ipynb/fixtures/py/complex_outputs.py+++ b/tests/_convert/ipynb/fixtures/py/complex_outputs.py@@ -1,12 +1,13 @@import marimo-__generated_with = "0.19.2"+__generated_with = "0.0.0"app = marimo.App()@app.celldef _():import marimo as mo+return (mo,)diff --git a/tests/_convert/ipynb/fixtures/py/markdown_variants.py b/tests/_convert/ipynb/fixtures/py/markdown_variants.pynew file mode 100644index 0000000000..75cb11dd41--- /dev/null+++ b/tests/_convert/ipynb/fixtures/py/markdown_variants.py@@ -0,0 +1,67 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ import marimo as mo++ return (mo,)+++def _():+ x = 42+ return (x,)+++def _(mo):+ mo.md("""+ # No prefix++ Plain triple-quoted markdown.+ """)+ return+++def _(mo):+ mo.md(r"""+ # R-prefix++ Raw triple-quoted markdown.+ """)+ return+++def _(mo):+ mo.md(f"""+ # F-prefix++ F-string with no interpolation.+ """)+ return+++def _(mo):+ mo.md(fr"""+ # FR-prefix++ FR-string with no interpolation.+ """)+ return+++def _(mo, x):+ mo.md(f"The value is **{x}**")+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/ipynb/fixtures/py/notebook_metadata.py b/tests/_convert/ipynb/fixtures/py/notebook_metadata.pynew file mode 100644index 0000000000..7e9efab8d0--- /dev/null+++ b/tests/_convert/ipynb/fixtures/py/notebook_metadata.py@@ -0,0 +1,28 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "numpy",+# ]+# ///++import marimo++__generated_with = "0.0.0"+app = marimo.App(width="medium", auto_download=["html"])+++def _():+ x = 1+ return (x,)+++def _(x):+ print(x)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/ipynb/fixtures/py/setup_cell.py b/tests/_convert/ipynb/fixtures/py/setup_cell.pynew file mode 100644index 0000000000..d24f0c394a--- /dev/null+++ b/tests/_convert/ipynb/fixtures/py/setup_cell.py@@ -0,0 +1,25 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()++with app.setup:+ import marimo as mo+++def _():+ mo.md("""+ # Hello from setup+ """)+ return+++def _():+ x = 42+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/ipynb/fixtures/py/simple.py b/tests/_convert/ipynb/fixtures/py/simple.pyindex 92f69c97a2..2bd8316c33 100644--- a/tests/_convert/ipynb/fixtures/py/simple.py+++ b/tests/_convert/ipynb/fixtures/py/simple.py@@ -1,12 +1,13 @@import marimo-__generated_with = "0.19.2"+__generated_with = "0.0.0"app = marimo.App()@app.celldef _():import marimo as mo+return (mo,)diff --git a/tests/_convert/ipynb/snapshots/app_config_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/app_config_top_down.ipynb.txtnew file mode 100644index 0000000000..dc5f63bfaf--- /dev/null+++ b/tests/_convert/ipynb/snapshots/app_config_top_down.ipynb.txt@@ -0,0 +1,48 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(x)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "app_config": {+ "auto_download": [+ "html"+ ],+ "width": "medium"+ },+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/cell_config_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/cell_config_top_down.ipynb.txtnew file mode 100644index 0000000000..ef87201555--- /dev/null+++ b/tests/_convert/ipynb/snapshots/cell_config_top_down.ipynb.txt@@ -0,0 +1,83 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "import marimo as mo"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "vblA",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ },+ "md_prefix": ""+ }+ },+ "source": [+ "# This cell is hidden"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "bkHC",+ "metadata": {+ "marimo": {+ "config": {+ "disabled": true+ }+ }+ },+ "outputs": [],+ "source": [+ "y = x + 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "lEQa",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(y)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/cell_names_and_defs_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/cell_names_and_defs_top_down.ipynb.txtnew file mode 100644index 0000000000..e7e45bbb9d--- /dev/null+++ b/tests/_convert/ipynb/snapshots/cell_names_and_defs_top_down.ipynb.txt@@ -0,0 +1,135 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {+ "marimo": {+ "name": "my_imports"+ }+ },+ "outputs": [],+ "source": [+ "import os\n",+ "import sys"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {+ "marimo": {+ "name": "compute"+ }+ },+ "outputs": [],+ "source": [+ "result = os.getcwd() + sys.platform"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "vblA",+ "metadata": {+ "marimo": {+ "name": "display"+ }+ },+ "outputs": [],+ "source": [+ "print(result)"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "bkHC",+ "metadata": {+ "marimo": {+ "name": "*add"+ }+ },+ "outputs": [],+ "source": [+ "def add(a, b):\n",+ " return a + b"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "lEQa",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ },+ "name": "*subtract"+ }+ },+ "outputs": [],+ "source": [+ "def subtract(a, b):\n",+ " return a - b"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "PKri",+ "metadata": {+ "marimo": {+ "name": "*MyClass"+ }+ },+ "outputs": [],+ "source": [+ "class MyClass:\n",+ " def __init__(self, val):\n",+ " self.val = val\n",+ " def double(self):\n",+ " return self.val * 2"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Xref",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ },+ "name": "*HiddenClass"+ }+ },+ "outputs": [],+ "source": [+ "class HiddenClass:\n",+ " def __init__(self, val):\n",+ " self.val = val"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/cell_names_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/cell_names_top_down.ipynb.txtnew file mode 100644index 0000000000..309c9821da--- /dev/null+++ b/tests/_convert/ipynb/snapshots/cell_names_top_down.ipynb.txt@@ -0,0 +1,65 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {+ "marimo": {+ "name": "my_imports"+ }+ },+ "outputs": [],+ "source": [+ "import os\n",+ "import sys"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {+ "marimo": {+ "name": "compute"+ }+ },+ "outputs": [],+ "source": [+ "result = os.getcwd() + sys.platform"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "vblA",+ "metadata": {+ "marimo": {+ "name": "display"+ }+ },+ "outputs": [],+ "source": [+ "print(result)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/complex_file_format_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/complex_file_format_top_down.ipynb.txtindex bd1863d2a3..a018546952 100644--- a/tests/_convert/ipynb/snapshots/complex_file_format_top_down.ipynb.txt+++ b/tests/_convert/ipynb/snapshots/complex_file_format_top_down.ipynb.txt@@ -22,7 +22,8 @@"marimo": {"config": {"hide_code": true- }+ },+ "md_prefix": ""}},"source": [diff --git a/tests/_convert/ipynb/snapshots/complex_outputs_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/complex_outputs_top_down.ipynb.txtindex 9f9fcbf7ca..ad8440a032 100644--- a/tests/_convert/ipynb/snapshots/complex_outputs_top_down.ipynb.txt+++ b/tests/_convert/ipynb/snapshots/complex_outputs_top_down.ipynb.txt@@ -13,7 +13,11 @@{"cell_type": "markdown","id": "MJUe",- "metadata": {},+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },"source": ["# Testing Various Output Types\n","\n",diff --git a/tests/_convert/ipynb/snapshots/disabled_cell_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/disabled_cell_top_down.ipynb.txtnew file mode 100644index 0000000000..e02b936ed4--- /dev/null+++ b/tests/_convert/ipynb/snapshots/disabled_cell_top_down.ipynb.txt@@ -0,0 +1,58 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {+ "marimo": {+ "config": {+ "disabled": true+ }+ }+ },+ "outputs": [],+ "source": [+ "y = x + 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "vblA",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(y)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/function_and_class_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/function_and_class_top_down.ipynb.txtnew file mode 100644index 0000000000..53a0e24f3f--- /dev/null+++ b/tests/_convert/ipynb/snapshots/function_and_class_top_down.ipynb.txt@@ -0,0 +1,102 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {+ "marimo": {+ "name": "*add"+ }+ },+ "outputs": [],+ "source": [+ "def add(a, b):\n",+ " return a + b"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "vblA",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ },+ "name": "*subtract"+ }+ },+ "outputs": [],+ "source": [+ "def subtract(a, b):\n",+ " return a - b"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "bkHC",+ "metadata": {+ "marimo": {+ "name": "*MyClass"+ }+ },+ "outputs": [],+ "source": [+ "class MyClass:\n",+ " def __init__(self, val):\n",+ " self.val = val\n",+ " def double(self):\n",+ " return self.val * 2"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "lEQa",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ },+ "name": "*HiddenClass"+ }+ },+ "outputs": [],+ "source": [+ "class HiddenClass:\n",+ " def __init__(self, val):\n",+ " self.val = val"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/hide_code_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/hide_code_top_down.ipynb.txtnew file mode 100644index 0000000000..a06d2eb6cd--- /dev/null+++ b/tests/_convert/ipynb/snapshots/hide_code_top_down.ipynb.txt@@ -0,0 +1,56 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "import marimo as mo"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "MJUe",+ "metadata": {+ "marimo": {+ "config": {+ "hide_code": true+ }+ }+ },+ "source": [+ "# This cell is hidden"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "vblA",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/markdown_variants_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/markdown_variants_top_down.ipynb.txtnew file mode 100644index 0000000000..9f15e213eb--- /dev/null+++ b/tests/_convert/ipynb/snapshots/markdown_variants_top_down.ipynb.txt@@ -0,0 +1,108 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "import marimo as mo"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 42"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "vblA",+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },+ "source": [+ "# No prefix\n",+ "\n",+ "Plain triple-quoted markdown."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "bkHC",+ "metadata": {+ "marimo": {+ "md_prefix": "r"+ }+ },+ "source": [+ "# R-prefix\n",+ "\n",+ "Raw triple-quoted markdown."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "lEQa",+ "metadata": {+ "marimo": {+ "md_prefix": "f"+ }+ },+ "source": [+ "# F-prefix\n",+ "\n",+ "F-string with no interpolation."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "PKri",+ "metadata": {+ "marimo": {+ "md_prefix": "fr"+ }+ },+ "source": [+ "# FR-prefix\n",+ "\n",+ "FR-string with no interpolation."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Xref",+ "metadata": {},+ "outputs": [],+ "source": [+ "mo.md(f\"The value is **{x}**\")"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/notebook_metadata_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/notebook_metadata_top_down.ipynb.txtnew file mode 100644index 0000000000..c3be80ef2f--- /dev/null+++ b/tests/_convert/ipynb/snapshots/notebook_metadata_top_down.ipynb.txt@@ -0,0 +1,49 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(x)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "app_config": {+ "auto_download": [+ "html"+ ],+ "width": "medium"+ },+ "header": "# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\n# \"marimo\",\n# \"numpy\",\n# ]\n# ///\n\n",+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/pep723_header_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/pep723_header_top_down.ipynb.txtnew file mode 100644index 0000000000..bae79bde5a--- /dev/null+++ b/tests/_convert/ipynb/snapshots/pep723_header_top_down.ipynb.txt@@ -0,0 +1,43 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "Hbol",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 1"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "print(x)"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "header": "# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\n# \"marimo\",\n# \"numpy\",\n# ]\n# ///\n\n",+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/setup_cell_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/setup_cell_top_down.ipynb.txtnew file mode 100644index 0000000000..8aa72e6e48--- /dev/null+++ b/tests/_convert/ipynb/snapshots/setup_cell_top_down.ipynb.txt@@ -0,0 +1,58 @@+{+ "cells": [+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "setup",+ "metadata": {+ "marimo": {+ "name": "setup"+ }+ },+ "outputs": [],+ "source": [+ "import marimo as mo"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "Hbol",+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },+ "source": [+ "# Hello from setup"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "MJUe",+ "metadata": {},+ "outputs": [],+ "source": [+ "x = 42"+ ]+ }+ ],+ "metadata": {+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3"+ },+ "marimo": {+ "marimo_version": "0.0.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}\ No newline at end of filediff --git a/tests/_convert/ipynb/snapshots/simple_top_down.ipynb.txt b/tests/_convert/ipynb/snapshots/simple_top_down.ipynb.txtindex 204df07fa8..0b3c826f17 100644--- a/tests/_convert/ipynb/snapshots/simple_top_down.ipynb.txt+++ b/tests/_convert/ipynb/snapshots/simple_top_down.ipynb.txt@@ -13,7 +13,11 @@{"cell_type": "markdown","id": "MJUe",- "metadata": {},+ "metadata": {+ "marimo": {+ "md_prefix": ""+ }+ },"source": ["# Hello, World!"]diff --git a/tests/_convert/ipynb/test_ipynb_idempotent.py b/tests/_convert/ipynb/test_ipynb_idempotent.pynew file mode 100644index 0000000000..e08ac78394--- /dev/null+++ b/tests/_convert/ipynb/test_ipynb_idempotent.py@@ -0,0 +1,201 @@+from __future__ import annotations++import functools+import pathlib++import pytest++pytest.importorskip("nbformat")++from marimo import __version__+from marimo._ast.app import InternalApp+from marimo._ast.load import load_app+from marimo._convert.converters import MarimoConvert+from marimo._convert.ipynb import (+ convert_from_ipynb_to_notebook_ir,+ convert_from_ir_to_ipynb,+)++SELF_DIR = pathlib.Path(__file__).parent+FIXTURES_PY = SELF_DIR / "fixtures" / "py"+++def sanitized_version(output: str) -> str:+ """Replace the current marimo version with 0.0.0 for stable comparison."""+ return output.replace(__version__, "0.0.0")+++def roundtrip(py_path: pathlib.Path) -> str:+ """Load a .py marimo file, export to ipynb, re-import, and return .py."""+ app = load_app(py_path)+ assert app+ internal_app = InternalApp(app)+ ipynb_str = convert_from_ir_to_ipynb(internal_app, sort_mode="top-down")+ ir = convert_from_ipynb_to_notebook_ir(ipynb_str)+ return sanitized_version(MarimoConvert.from_ir(ir).to_py())+++def assert_roundtrip(fixture_name: str) -> None:+ """Assert that a fixture file survives a py -> ipynb -> py round-trip."""+ py_path = FIXTURES_PY / fixture_name+ assert py_path.exists(), f"Fixture not found: {py_path}"+ expected = py_path.read_text()+ actual = roundtrip(py_path)+ assert expected == actual+++# --- Parametrized test over all fixtures ---+++PY_FIXTURES = sorted(FIXTURES_PY.glob("*.py"))+++ "py_path", PY_FIXTURES, ids=[p.stem for p in PY_FIXTURES]+)+def test_ipynb_idempotent(py_path: pathlib.Path) -> None:+ expected = py_path.read_text()+ actual = roundtrip(py_path)+ assert expected == actual+++# --- Individual focused tests ---+++class TestCellNamesAndDefs:+ """Cell names, @app.function, and @app.class_definition should+ survive round-trip."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("cell_names_and_defs.py")++ def test_named_cells_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "cell_names_and_defs.py")+ assert "def my_imports():" in result+ assert "def compute(os, sys):" in result+ assert "def display(result):" in result++ def test_function_decorators_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "cell_names_and_defs.py")+ assert "@app.function\n" in result+ assert "@app.function(hide_code=True)" in result+ assert "@app.class_definition\n" in result+ assert "@app.class_definition(hide_code=True)" in result++ def test_function_and_class_names_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "cell_names_and_defs.py")+ assert "def add(a, b):" in result+ assert "def subtract(a, b):" in result+ assert "class MyClass:" in result+ assert "class HiddenClass:" in result+++class TestSetupCell:+ """with app.setup: block should survive round-trip."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("setup_cell.py")++ def test_setup_block_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "setup_cell.py")+ assert "with app.setup:" in result+ lines = result.split("\n")+ for i, line in enumerate(lines):+ if "import marimo as mo" in line and i > 0:+ prev_lines = [line for line in lines[:i] if line.strip()]+ assert prev_lines[-1].strip() == "with app.setup:"+ break+++class TestCellConfig:+ """Cell configuration (hide_code, disabled) should survive round-trip."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("cell_config.py")++ def test_hide_code_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "cell_config.py")+ assert "@app.cell(hide_code=True)" in result++ def test_disabled_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "cell_config.py")+ assert "@app.cell(disabled=True)" in result+++class TestMarkdownStringPrefix:+ """String prefix on mo.md() calls should survive round-trip."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("markdown_variants.py")++ def test_no_prefix_does_not_gain_r(self) -> None:+ """mo.md(triple-quote) without r should not gain r prefix."""+ result = roundtrip(FIXTURES_PY / "markdown_variants.py")+ assert 'mo.md("""\n # No prefix' in result++ def test_r_prefix_preserved(self) -> None:+ result = roundtrip(FIXTURES_PY / "markdown_variants.py")+ assert 'mo.md(r"""\n # R-prefix' in result++ def test_f_prefix_preserved(self) -> None:+ """mo.md(f-triple-quote) with no interpolation should keep f prefix."""+ result = roundtrip(FIXTURES_PY / "markdown_variants.py")+ assert 'mo.md(f"""\n # F-prefix' in result++ def test_fr_prefix_preserved(self) -> None:+ """mo.md(fr-triple-quote) with no interpolation should keep fr prefix."""+ result = roundtrip(FIXTURES_PY / "markdown_variants.py")+ assert 'mo.md(fr"""\n # FR-prefix' in result++ def test_f_with_interpolation_survives(self) -> None:+ """mo.md(f"...{var}...") stays as code cell, not extracted as markdown."""+ result = roundtrip(FIXTURES_PY / "markdown_variants.py")+ assert 'mo.md(f"The value is **{x}**")' in result+++class TestNotebookMetadata:+ """App config and PEP 723 header should survive round-trip."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("notebook_metadata.py")++ def test_app_config_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "notebook_metadata.py")+ assert 'width="medium"' in result+ assert 'auto_download=["html"]' in result++ def test_pep723_header_in_output(self) -> None:+ result = roundtrip(FIXTURES_PY / "notebook_metadata.py")+ assert "# /// script" in result+ assert 'requires-python = ">=3.12"' in result+ assert '"numpy"' in result+++class TestGeneratedWithVersion:+ """__generated_with should use the converting marimo version."""++ def test_roundtrip(self) -> None:+ assert_roundtrip("simple.py")++ def test_version_string_in_output(self) -> None:+ """Conversion uses the current marimo version, not the original."""+ app = load_app(FIXTURES_PY / "simple.py")+ assert app+ internal_app = InternalApp(app)+ ipynb_str = convert_from_ir_to_ipynb(+ internal_app, sort_mode="top-down"+ )+ ir = convert_from_ipynb_to_notebook_ir(ipynb_str)+ result = MarimoConvert.from_ir(ir).to_py()+ assert f'__generated_with = "{__version__}"' in result+++class TestComplexFixtures:+ """Integration tests with complex fixtures combining multiple features."""++ def test_complex_file_format(self) -> None:+ assert_roundtrip("complex_file_format.py")++ def test_complex_outputs(self) -> None:+ assert_roundtrip("complex_outputs.py")