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.

Support some JupyterBook cell tags in marimo convert (#5169)

Trevor Manz92e6a048c99a
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.py
index 012f36cce9..c17dd544bc 100644
--- a/marimo/_convert/ipynb.py
+++ b/marimo/_convert/ipynb.py
@@ -6,6 +6,7 @@ import json
import re
import sys
from collections import defaultdict
+from dataclasses import dataclass, field
from typing import Any, Callable, Union
from marimo._ast.cell import CellConfig
@@ -23,10 +24,20 @@ from marimo._schemas.serialization import (
)
from marimo._types.ids import CellId_t
-# Define a type for our transform functions
+# Define a type for our 1:1 source-only transform functions
Transform = Callable[[list[str]], list[str]]
+@dataclass
+class CodeCell:
+ source: str
+ config: CellConfig = field(default_factory=CellConfig)
+
+
+# Define a type for transforms that add/remove cells
+CellsTransform = Callable[[list[CodeCell]], list[CodeCell]]
+
+
def transform_fixup_multiple_definitions(sources: list[str]) -> list[str]:
"""
Fixup multiple definitions of the same name in different cells,
@@ -74,7 +85,7 @@ def transform_fixup_multiple_definitions(sources: list[str]) -> list[str]:
return [transform(source) for source in sources]
-def transform_add_marimo_import(sources: list[str]) -> list[str]:
+def transform_add_marimo_import(sources: list[CodeCell]) -> list[CodeCell]:
"""
Add an import statement for marimo if any cell uses
the `mo.md` or `mo.sql` functions.
@@ -102,13 +113,13 @@ def transform_add_marimo_import(sources: list[str]) -> list[str]:
return False
already_has_marimo_import = any(
- has_marimo_import(cell) for cell in sources
+ has_marimo_import(cell.source) for cell in sources
)
if already_has_marimo_import:
return sources
- if any(contains_mo(cell) for cell in sources):
- return sources + ["import marimo as mo"]
+ if any(contains_mo(cell.source) for cell in sources):
+ return sources + [CodeCell("import marimo as mo")]
return sources
@@ -608,22 +619,29 @@ def transform_duplicate_definitions(sources: list[str]) -> list[str]:
return new_sources
-def transform_cell_metadata(
- sources: list[str], metadata: list[dict[str, Any]]
-) -> list[str]:
+def bind_cell_metadata(
+ sources: list[str], metadata: list[dict[str, Any]], hide_flags: list[bool]
+) -> list[CodeCell]:
"""
- Handle cell metadata, such as tags or cell IDs.
+ One-time transformation that binds sources and (ipynb) metadata into CodeCell objects.
+
+ This marks the boundary between source-only transformations and cell-level transformations.
+
+ - If "hide-cell" is present in the tags, the cell is marked hidden (and removed)
+ - Remaining tags (if any) are inserted as a comment at the top of the source.
"""
- transformed_sources: list[str] = []
- for source, meta in zip(sources, metadata):
- if "tags" in meta:
- tags = meta["tags"]
- if not tags:
- transformed_sources.append(source)
- continue
- source = f"# Cell tags: {', '.join(tags)}\n{source}"
- transformed_sources.append(source)
- return transformed_sources
+ 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}"
+ cells.append(
+ CodeCell(source=source, config=CellConfig(hide_code=hide_code))
+ )
+ return cells
def transform_remove_duplicate_imports(sources: list[str]) -> list[str]:
@@ -651,14 +669,14 @@ def transform_remove_duplicate_imports(sources: list[str]) -> list[str]:
return new_sources
-def transform_remove_empty_cells(sources: list[str]) -> list[str]:
+def transform_remove_empty_cells(cells: list[CodeCell]) -> list[CodeCell]:
"""
Remove empty cells.
"""
- sources = [source for source in sources if source.strip()]
+ sources = [cell for cell in cells if cell.source.strip()]
# Ensure there is at least one cell
if not sources:
- return [""]
+ return [CodeCell("")]
return sources
@@ -685,23 +703,46 @@ def extract_inline_meta(script: str) -> tuple[str | None, str]:
def _transform_sources(
- sources: list[str], metadata: list[dict[str, Any]]
-) -> list[str]:
- transforms: list[Transform] = [
+ sources: list[str], metadata: list[dict[str, Any]], hide_flags: list[bool]
+) -> list[CodeCell]:
+ """
+ Process raw sources and metadata into finalized cells.
+
+ This pipeline runs in three stages:
+ 1. Source-only transforms (e.g., stripping whitespace, handling magics)
+ 2. A one-time binding of sources and metadata.
+ 3. Cell-level transforms (e.g., inserting imports, removing empty cells)
+
+ After this step, cells are ready for execution or rendering.
+ """
+ source_transforms: list[Transform] = [
transform_strip_whitespace,
transform_magic_commands,
transform_remove_duplicate_imports,
transform_fixup_multiple_definitions,
transform_duplicate_definitions,
- lambda s: transform_cell_metadata(s, metadata),
- transform_add_marimo_import, # may change cell count
- transform_remove_empty_cells, # may change cell count
]
- # Run all the transforms
- for transform in transforms:
- sources = transform(sources)
- return sources
+ # Run all the source transforms
+ for source_transform in source_transforms:
+ new_sources = source_transform(sources)
+ assert len(new_sources) == len(sources), (
+ f"{source_transform.__name__} changed cell count"
+ )
+ sources = new_sources
+
+ cells = bind_cell_metadata(sources, metadata, hide_flags)
+
+ # may change cell count
+ cell_transforms: list[CellsTransform] = [
+ transform_add_marimo_import,
+ transform_remove_empty_cells,
+ ]
+
+ for cell_transform in cell_transforms:
+ cells = cell_transform(cells)
+
+ return cells
def convert_from_ipynb_to_notebook_ir(
@@ -713,9 +754,8 @@ def convert_from_ipynb_to_notebook_ir(
notebook = json.loads(raw_notebook)
sources: list[str] = []
metadata: list[dict[str, Any]] = []
- cell_configs: list[CellConfig] = []
+ hide_flags: list[bool] = []
inline_meta: Union[str, None] = None
- md_cells: set[str] = set()
for cell in notebook["cells"]:
source = (
@@ -726,7 +766,6 @@ def convert_from_ipynb_to_notebook_ir(
is_markdown: bool = cell["cell_type"] == "markdown"
if is_markdown:
source = markdown_to_marimo(source)
- md_cells.add(source)
elif inline_meta is None:
# Eagerly find PEP 723 metadata, first match wins
inline_meta, source = extract_inline_meta(source)
@@ -734,23 +773,18 @@ def convert_from_ipynb_to_notebook_ir(
if source:
sources.append(source)
metadata.append(cell.get("metadata", {}))
+ hide_flags.append(is_markdown)
- transformed_sources = _transform_sources(sources, metadata)
-
- # Cell configs must come after _transform_sources since this may add/remove cells
- cell_configs = [
- CellConfig(hide_code=source in md_cells)
- for source in transformed_sources
- ]
+ transformed_cells = _transform_sources(sources, metadata, hide_flags)
return NotebookSerializationV1(
app=AppInstantiation(),
header=Header(value=inline_meta or ""),
cells=[
CellDef(
- code=source,
- options={"hide_code": config.hide_code},
+ code=cell.source,
+ options={"hide_code": cell.config.hide_code},
)
- for source, config in zip(transformed_sources, cell_configs)
+ for cell in transformed_cells
],
)
diff --git a/scripts/generate_ipynb_fixtures.py b/scripts/generate_ipynb_fixtures.py
index ebc108d609..6b0955037e 100644
--- a/scripts/generate_ipynb_fixtures.py
+++ b/scripts/generate_ipynb_fixtures.py
@@ -22,7 +22,6 @@ Output notebooks are written to `tests/_convert/ipynb_data/`.
"""
from __future__ import annotations
-from io import FileIO
from pathlib import Path
import nbformat.v4.nbbase as nb
@@ -102,6 +101,61 @@ for i_1 in range(X_1.shape[0]):
],
)
+ create_notebook_fixture(
+ "cell_metadata",
+ [
+ nb.new_code_cell(
+ "print('Hello')", metadata={"tags": ["tag1", "tag2"]}
+ ),
+ nb.new_code_cell("print('World')", metadata={}),
+ nb.new_code_cell(
+ "print('Cell 1')",
+ metadata={"tags": ["important", "data-processing"]},
+ ),
+ nb.new_code_cell("print('Cell 2')", metadata={"tags": []}),
+ nb.new_code_cell(
+ "print('Cell 3')",
+ metadata={"tags": ["visualization"], "collapsed": True},
+ ),
+ nb.new_code_cell(
+ "print('Complex metadata')",
+ metadata={
+ "tags": ["tag1", "tag2"],
+ "collapsed": True,
+ "scrolled": False,
+ "custom": {"key": "value"},
+ },
+ ),
+ nb.new_code_cell(
+ "print('hidden cell')",
+ metadata={
+ "tags": ["hide-cell"],
+ },
+ ),
+ nb.new_code_cell(
+ "print('hidden cell, with other tags')",
+ metadata={
+ "tags": ["hide-cell", "remove-print"],
+ },
+ ),
+ ],
+ )
+
+ create_notebook_fixture(
+ "hides_markdown_cells",
+ [
+ nb.new_markdown_cell("A markdown cell."),
+ nb.new_markdown_cell(
+ "A markdown cell with tags: ['blah'].",
+ metadata={"tags": ["blah"]},
+ ),
+ nb.new_markdown_cell(
+ "A markdown cell with tags: ['blah', 'hide-cell'].",
+ metadata={"tags": ["blah", "hide-cell"]},
+ ),
+ ],
+ )
+
if __name__ == "__main__":
main()
diff --git a/tests/_convert/ipynb_data/cell_metadata.ipynb b/tests/_convert/ipynb_data/cell_metadata.ipynb
new file mode 100644
index 0000000000..87ea83346a
--- /dev/null
+++ b/tests/_convert/ipynb_data/cell_metadata.ipynb
@@ -0,0 +1,123 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0",
+ "metadata": {
+ "tags": [
+ "tag1",
+ "tag2"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('Hello')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print('World')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "2",
+ "metadata": {
+ "tags": [
+ "important",
+ "data-processing"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('Cell 1')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "3",
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "print('Cell 2')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4",
+ "metadata": {
+ "collapsed": true,
+ "tags": [
+ "visualization"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('Cell 3')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "5",
+ "metadata": {
+ "collapsed": true,
+ "custom": {
+ "key": "value"
+ },
+ "scrolled": false,
+ "tags": [
+ "tag1",
+ "tag2"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('Complex metadata')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6",
+ "metadata": {
+ "tags": [
+ "hide-cell"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('hidden cell')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7",
+ "metadata": {
+ "tags": [
+ "hide-cell",
+ "remove-print"
+ ]
+ },
+ "outputs": [],
+ "source": [
+ "print('hidden cell, with other tags')"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_convert/ipynb_data/hides_markdown_cells.ipynb b/tests/_convert/ipynb_data/hides_markdown_cells.ipynb
new file mode 100644
index 0000000000..4d429cddd9
--- /dev/null
+++ b/tests/_convert/ipynb_data/hides_markdown_cells.ipynb
@@ -0,0 +1,40 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "0",
+ "metadata": {},
+ "source": [
+ "A markdown cell."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1",
+ "metadata": {
+ "tags": [
+ "blah"
+ ]
+ },
+ "source": [
+ "A markdown cell with tags: ['blah']."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2",
+ "metadata": {
+ "tags": [
+ "blah",
+ "hide-cell"
+ ]
+ },
+ "source": [
+ "A markdown cell with tags: ['blah', 'hide-cell']."
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_convert/snapshots/convert_cell_metadata.py.txt b/tests/_convert/snapshots/convert_cell_metadata.py.txt
new file mode 100644
index 0000000000..35ff989012
--- /dev/null
+++ b/tests/_convert/snapshots/convert_cell_metadata.py.txt
@@ -0,0 +1,60 @@
+import marimo
+
+app = marimo.App()
+
+
+def _():
+ # Cell tags: tag1, tag2
+ print('Hello')
+ return
+
+
+def _():
+ print('World')
+ return
+
+
+def _():
+ # Cell tags: data-processing, important
+ print('Cell 1')
+ return
+
+
+def _():
+ print('Cell 2')
+ return
+
+
+def _():
+ # Cell tags: visualization
+ print('Cell 3')
+ return
+
+
+def _():
+ # Cell tags: tag1, tag2
+ print('Complex metadata')
+ return
+
+
[email protected](hide_code=True)
+def _():
+ print('hidden cell')
+ return
+
+
[email protected](hide_code=True)
+def _():
+ # Cell tags: remove-print
+ print('hidden cell, with other tags')
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_convert/snapshots/convert_hides_markdown_cells.py.txt b/tests/_convert/snapshots/convert_hides_markdown_cells.py.txt
new file mode 100644
index 0000000000..8071efd075
--- /dev/null
+++ b/tests/_convert/snapshots/convert_hides_markdown_cells.py.txt
@@ -0,0 +1,45 @@
+import marimo
+
+app = marimo.App()
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ A markdown cell.
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ # Cell tags: blah
+ mo.md(
+ r"""
+ A markdown cell with tags: ['blah'].
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ # Cell tags: blah
+ mo.md(
+ r"""
+ A markdown cell with tags: ['blah', 'hide-cell'].
+ """
+ )
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_convert/test_ipynb.py b/tests/_convert/test_ipynb.py
index 03e7bf935a..6a3eab5a1c 100644
--- a/tests/_convert/test_ipynb.py
+++ b/tests/_convert/test_ipynb.py
@@ -6,8 +6,10 @@ from textwrap import dedent
import pytest
from marimo._convert.ipynb import (
+ CellsTransform,
+ CodeCell,
+ Transform,
transform_add_marimo_import,
- transform_cell_metadata,
transform_duplicate_definitions,
transform_exclamation_mark,
transform_fixup_multiple_definitions,
@@ -20,6 +22,16 @@ def dd(sources: list[str]) -> list[str]:
return [dedent(s) for s in sources]
+def strip_cells(transform: CellsTransform) -> Transform:
+ """Test wrapper for cell transforms - extracts only source content for testing."""
+
+ def wrapped(sources: list[str]) -> list[str]:
+ cells = [CodeCell(s) for s in sources]
+ return [cell.source for cell in transform(cells)]
+
+ return wrapped
+
+
def assert_sources_equal(transformed: list[str], expected: list[str]) -> None:
expected = dd(expected)
assert len(transformed) == len(expected)
@@ -126,7 +138,7 @@ def test_transform_add_marimo_import():
"mo.md('# Hello')",
"print('World')",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert "import marimo as mo" in result
# mo.sql
@@ -134,13 +146,13 @@ def test_transform_add_marimo_import():
"mo.sql('SELECT * FROM table')",
"print('World')",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert "import marimo as mo" in result
# if `import marimo as mo` is already present
# it should not be added again
existing = sources + ["import marimo as mo"]
- assert transform_add_marimo_import(existing) == existing
+ assert strip_cells(transform_add_marimo_import)(existing) == existing
existing = [
# slight support for different import orders
@@ -148,7 +160,7 @@ def test_transform_add_marimo_import():
"import antigravity; import marimo as mo",
"mo.md('# Hello')",
]
- assert transform_add_marimo_import(existing) == existing
+ assert strip_cells(transform_add_marimo_import)(existing) == existing
def test_transform_add_marimo_import_already_imported():
@@ -157,7 +169,7 @@ def test_transform_add_marimo_import_already_imported():
"mo.md('# Hello')",
"print('World')",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert result == sources
@@ -167,7 +179,7 @@ def test_transform_add_marimo_import_already_but_in_comment_or_definition():
"mo.md('# Hello')",
"# import marimo as mo",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert result == sources + ["import marimo as mo"]
# Definition
@@ -175,7 +187,7 @@ def test_transform_add_marimo_import_already_but_in_comment_or_definition():
"mo.md('# Hello')",
"def foo():\n import marimo as mo",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert result == sources + ["import marimo as mo"]
@@ -275,22 +287,6 @@ def test_transform_duplicate_definitions():
]
-def test_transform_cell_metadata():
- sources = [
- "print('Hello')",
- "print('World')",
- ]
- metadata = [
- {"tags": ["tag1", "tag2"]},
- {},
- ]
- result = transform_cell_metadata(sources, metadata)
- assert result == [
- "# Cell tags: tag1, tag2\nprint('Hello')",
- "print('World')",
- ]
-
-
def test_transform_remove_duplicate_imports():
sources = [
"import numpy as np\nimport pandas as pd\nimport numpy as np",
@@ -353,7 +349,7 @@ def test_transform_add_marimo_import_edge_cases():
"print('mo.sql is not a real call')",
"mo = 'not the real mo'",
]
- result = transform_add_marimo_import(sources)
+ result = strip_cells(transform_add_marimo_import)(sources)
assert "import marimo as mo" not in result
@@ -417,25 +413,6 @@ def test_transform_duplicate_definitions_complex():
]
-def test_transform_cell_metadata_complex():
- sources = [
- "print('Cell 1')",
- "print('Cell 2')",
- "print('Cell 3')",
- ]
- metadata = [
- {"tags": ["important", "data-processing"]},
- {"tags": []},
- {"tags": ["visualization"], "collapsed": True},
- ]
- result = transform_cell_metadata(sources, metadata)
- assert result == [
- "# Cell tags: important, data-processing\nprint('Cell 1')",
- "print('Cell 2')",
- "# Cell tags: visualization\nprint('Cell 3')",
- ]
-
-
def test_transform_remove_duplicate_imports_complex():
sources = [
"import numpy as np\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt", # noqa: E501
@@ -518,24 +495,6 @@ def test_transform_duplicate_definitions_with_reference_to_previous():
]
-def test_transform_cell_metadata_with_complex_metadata():
- sources = [
- "print('Complex metadata')",
- ]
- metadata = [
- {
- "tags": ["tag1", "tag2"],
- "collapsed": True,
- "scrolled": False,
- "custom": {"key": "value"},
- }
- ]
- result = transform_cell_metadata(sources, metadata)
- assert result == [
- "# Cell tags: tag1, tag2\nprint('Complex metadata')",
- ]
-
-
def test_transform_remove_duplicate_imports_with_aliases():
sources = [
"import numpy as np\nimport pandas as pd",