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.

internal: internal api for template rendering (#7555)

Myles Scolnick1a67a1c6e7f4
diff --git a/marimo/_internal/__init__.py b/marimo/_internal/__init__.py
new file mode 100644
index 0000000000..a5aec03e68
--- /dev/null
+++ b/marimo/_internal/__init__.py
@@ -0,0 +1,5 @@
+"""Internal API - DO NOT USE."""
+
+import marimo._internal.templates as templates
+
+__all__ = ["templates"]
diff --git a/marimo/_internal/templates.py b/marimo/_internal/templates.py
new file mode 100644
index 0000000000..096d7acd7c
--- /dev/null
+++ b/marimo/_internal/templates.py
@@ -0,0 +1,12 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""Internal API for rendering marimo notebooks as HTML."""
+
+from marimo._server.templates.api import (
+ render_notebook,
+ render_static_notebook,
+)
+
+__all__ = [
+ "render_notebook",
+ "render_static_notebook",
+]
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 09bdd03ec8..b7e8e0cd1f 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -153,7 +153,9 @@ async def index(request: Request) -> HTMLResponse:
app_config=app_config,
filename=app_manager.filename,
mode=app_state.mode,
- remote_url=app_state.remote_url,
+ runtime_config=[{"url": app_state.remote_url}]
+ if app_state.remote_url
+ else None,
asset_url=app_state.asset_url,
)
diff --git a/marimo/_server/templates/api.py b/marimo/_server/templates/api.py
new file mode 100644
index 0000000000..0b760eec70
--- /dev/null
+++ b/marimo/_server/templates/api.py
@@ -0,0 +1,247 @@
+# Copyright 2024 Marimo. All rights reserved.
+"""Public API for rendering marimo notebooks as HTML.
+
+This module provides a clean, public API for rendering marimo notebooks
+to HTML without needing to use internal template functions directly.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any, Literal, Optional, cast
+
+from marimo._ast.app_config import _AppConfig
+from marimo._config.config import MarimoConfig, PartialMarimoConfig
+from marimo._convert.converters import MarimoConvert
+from marimo._schemas.notebook import NotebookV1
+from marimo._schemas.session import NotebookSessionV1
+from marimo._server.model import SessionMode
+from marimo._server.templates.templates import (
+ _custom_css_block,
+ notebook_page_template,
+ static_notebook_template,
+)
+from marimo._server.tokens import SkewProtectionToken
+from marimo._utils.code import hash_code
+
+
+def _get_html_template() -> str:
+ """Get the base HTML template."""
+ from marimo._utils.paths import marimo_package_path
+
+ index_html = Path(marimo_package_path()) / "_static" / "index.html"
+ return index_html.read_text(encoding="utf-8")
+
+
+def _parse_config(config: Optional[dict[str, Any]]) -> MarimoConfig:
+ """Parse config dict to MarimoConfig."""
+ if config is None:
+ return cast(MarimoConfig, {})
+ return cast(MarimoConfig, config)
+
+
+def _parse_partial_config(
+ config: Optional[dict[str, Any]],
+) -> PartialMarimoConfig:
+ """Parse config dict to PartialMarimoConfig."""
+ if config is None:
+ return cast(PartialMarimoConfig, {})
+ return cast(PartialMarimoConfig, config)
+
+
+def _convert_code_to_notebook(
+ code: str,
+) -> tuple[NotebookV1, _AppConfig]:
+ """Convert Python code to notebook format."""
+ try:
+ ir = MarimoConvert.from_py(code)
+ except Exception:
+ # Fallback to non-marimo script conversion
+ ir = MarimoConvert.from_non_marimo_python_script(code, aggressive=True)
+
+ app_config = _AppConfig.from_untrusted_dict(ir.ir.app.options)
+ notebook = cast(NotebookV1, ir.to_notebook_v1())
+ return notebook, app_config
+
+
+def render_notebook(
+ *,
+ code: str,
+ mode: Literal["edit", "read"],
+ filename: str | None = None,
+ config: dict[str, Any] | None = None,
+ config_overrides: dict[str, Any] | None = None,
+ app_config: dict[str, Any] | None = None,
+ runtime_config: list[dict[str, Any]] | None = None,
+ server_token: str | None = None,
+ session_snapshot: NotebookSessionV1 | None = None,
+ notebook_snapshot: NotebookV1 | None = None,
+ base_url: str = "",
+ asset_url: str | None = None,
+ custom_css: str | None = None,
+) -> str:
+ """Render a marimo notebook to HTML.
+
+ Handles all the conversions internally.
+
+ Args:
+ code: Raw Python code as a string.
+ filename: Display filename.
+ mode: Rendering mode - "edit" for editable, "read" for read-only.
+ config: User configuration overrides as a dict.
+ config_overrides: Notebook-specific configuration overrides as a dict.
+ app_config: Notebook-specific configuration as a dict.
+ runtime_config: Remote kernel configuration, e.g.,
+ [{"url": "wss://...", "authToken": "..."}]
+ server_token: Skew protection token.
+ session_snapshot: Pre-computed session state.
+ notebook_snapshot: Notebook structure/metadata.
+ base_url: Base URL for the application (for <base> tag).
+ asset_url: CDN URL for static assets (supports {version} placeholder).
+ custom_css: CSS string to inject directly into the HTML.
+
+ Returns:
+ HTML string of the rendered notebook.
+
+ Example:
+ >>> html = render_notebook(
+ ... code="import marimo as mo\\nmo.md('Hello')",
+ ... filename="notebook.py",
+ ... mode="edit",
+ ... runtime_config=[{"url": "wss://kernel.example.com"}],
+ ... )
+ """
+
+ # Convert code to notebook format if not already provided
+ if notebook_snapshot is None or app_config is None:
+ converted_notebook, converted_app_config = _convert_code_to_notebook(
+ code
+ )
+ if notebook_snapshot is None:
+ notebook_snapshot = converted_notebook
+ if app_config is None:
+ app_config = converted_app_config.asdict()
+
+ # Parse configs
+ user_config = _parse_config(config)
+ config_overrides_obj = _parse_partial_config(config_overrides)
+ app_config_obj = _AppConfig.from_untrusted_dict(app_config)
+
+ # Get HTML template
+ html = _get_html_template()
+
+ result = notebook_page_template(
+ html=html,
+ base_url=base_url,
+ user_config=user_config,
+ config_overrides=config_overrides_obj,
+ server_token=SkewProtectionToken(server_token or ""),
+ app_config=app_config_obj,
+ filename=filename,
+ mode=_parse_session_mode(mode),
+ session_snapshot=session_snapshot,
+ notebook_snapshot=notebook_snapshot,
+ runtime_config=runtime_config,
+ asset_url=asset_url,
+ )
+
+ # Add custom CSS if provided
+ if custom_css:
+ result = _add_custom_css(result, custom_css)
+
+ return result
+
+
+def render_static_notebook(
+ *,
+ code: str,
+ filename: str | None = None,
+ include_code: bool = True,
+ session_snapshot: NotebookSessionV1,
+ notebook_snapshot: NotebookV1 | None = None,
+ files: dict[str, str] | None = None,
+ config: dict[str, Any] | None = None,
+ app_config: dict[str, Any] | None = None,
+ asset_url: str | None = None,
+) -> str:
+ """Render a static (pre-computed) marimo notebook to HTML.
+
+ Creates a fully self-contained HTML file with pre-computed outputs.
+ Ideal for sharing read-only versions of notebooks.
+
+ Args:
+ code: Raw Python code as a string.
+ filename: Display filename.
+ include_code: Whether to include source code in the export.
+ session_snapshot: Pre-computed outputs for all cells (required).
+ notebook_snapshot: Notebook structure/metadata.
+ files: Files to embed (key=path, value=base64 content).
+ config: User configuration overrides.
+ app_config: Notebook-specific configuration.
+ asset_url: CDN URL for assets (default: jsDelivr).
+
+ Returns:
+ HTML string of the static notebook.
+
+ Example:
+ >>> html = render_static_notebook(
+ ... code=Path("analysis.py").read_text(),
+ ... session_snapshot=precomputed_outputs,
+ ... config={"theme": "dark"},
+ ... )
+ """
+
+ # Convert code to notebook format if not already provided
+ if notebook_snapshot is None or app_config is None:
+ converted_notebook, converted_app_config = _convert_code_to_notebook(
+ code
+ )
+ if notebook_snapshot is None:
+ notebook_snapshot = converted_notebook
+ if app_config is None:
+ app_config = converted_app_config.asdict()
+
+ # Parse configs
+ user_config = _parse_config(config)
+ config_overrides_obj = _parse_partial_config(config or {})
+ app_config_obj = _AppConfig.from_untrusted_dict(app_config)
+
+ # Get HTML template
+ html = _get_html_template()
+
+ return static_notebook_template(
+ html=html,
+ user_config=user_config,
+ config_overrides=config_overrides_obj,
+ server_token=SkewProtectionToken("static"),
+ app_config=app_config_obj,
+ filepath=filename,
+ code=code if include_code else "",
+ code_hash=hash_code(code),
+ session_snapshot=session_snapshot,
+ notebook_snapshot=notebook_snapshot,
+ files=files or {},
+ asset_url=asset_url,
+ )
+
+
+def _add_custom_css(html: str, custom_css: str) -> str:
+ css_block = _custom_css_block(custom_css)
+ return html.replace("</head>", f"{css_block}</head>")
+
+
+def _parse_session_mode(mode: Literal["edit", "read"]) -> SessionMode:
+ if mode == "edit":
+ return SessionMode.EDIT
+ elif mode in ["run", "read"]:
+ return SessionMode.RUN
+ else:
+ raise ValueError(
+ f"Invalid session mode: {mode}. Must be 'edit' or 'run'."
+ )
+
+
+__all__ = [
+ "render_notebook",
+ "render_static_notebook",
+]
diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.py
index 1bf4b4e281..f16fc3b8aa 100644
--- a/marimo/_server/templates/templates.py
+++ b/marimo/_server/templates/templates.py
@@ -54,7 +54,7 @@ def _get_mount_config(
show_app_code: bool = True,
session_snapshot: Optional[NotebookSessionV1] = None,
notebook_snapshot: Optional[NotebookV1] = None,
- remote_url: Optional[str] = None,
+ runtime_config: Optional[list[dict[str, Any]]] = None,
) -> str:
"""
Return a JSON string with custom indentation and sorting.
@@ -75,7 +75,7 @@ def _get_mount_config(
},
"notebook": notebook_snapshot,
"session": session_snapshot,
- "runtime_config": [{"url": remote_url}] if remote_url else None,
+ "runtime_config": runtime_config,
}
return """{{
@@ -124,7 +124,6 @@ def home_page_template(
user_config=user_config,
config_overrides=config_overrides,
app_config=None,
- remote_url=None,
),
)
@@ -135,6 +134,7 @@ def home_page_template(
def notebook_page_template(
+ *,
html: str,
base_url: str,
user_config: MarimoConfig,
@@ -143,15 +143,16 @@ def notebook_page_template(
app_config: _AppConfig,
filename: Optional[str],
mode: SessionMode,
- remote_url: Optional[str] = None,
+ session_snapshot: Optional[NotebookSessionV1] = None,
+ notebook_snapshot: Optional[NotebookV1] = None,
+ runtime_config: Optional[list[dict[str, Any]]] = None,
asset_url: Optional[str] = None,
) -> str:
html = html.replace("{{ base_url }}", base_url)
# When we have a remote URL, let's pre-populate the index.html page
# with a view of the notebook.
- notebook_snapshot = None
- if remote_url and filename:
+ if runtime_config and filename and notebook_snapshot is None:
filepath = Path(filename)
if filepath.exists():
notebook_snapshot = MarimoConvert.from_py(
@@ -178,8 +179,9 @@ def notebook_page_template(
user_config=user_config,
config_overrides=config_overrides,
app_config=app_config,
- remote_url=remote_url,
+ runtime_config=runtime_config,
notebook_snapshot=notebook_snapshot,
+ session_snapshot=session_snapshot,
),
)
@@ -252,7 +254,7 @@ def static_notebook_template(
app_config=app_config,
session_snapshot=session_snapshot,
notebook_snapshot=notebook_snapshot,
- remote_url=None,
+ runtime_config=None,
),
)
@@ -372,7 +374,7 @@ def wasm_notebook_template(
app_config=app_config,
version=version,
show_app_code=show_code,
- remote_url=None,
+ runtime_config=None,
),
)
diff --git a/tests/_internal/snapshots/internal_api.txt b/tests/_internal/snapshots/internal_api.txt
new file mode 100644
index 0000000000..03aef553c3
--- /dev/null
+++ b/tests/_internal/snapshots/internal_api.txt
@@ -0,0 +1,3 @@
+templates
+ render_notebook
+ render_static_notebook
\ No newline at end of file
diff --git a/tests/_internal/test_internal_api.py b/tests/_internal/test_internal_api.py
new file mode 100644
index 0000000000..cd53ac9d04
--- /dev/null
+++ b/tests/_internal/test_internal_api.py
@@ -0,0 +1,14 @@
+from __future__ import annotations
+
+from tests.mocks import snapshotter
+from tests.utils import explore_module
+
+snapshot = snapshotter(__file__)
+
+
+def test_internal_api():
+ import marimo._internal as internal
+
+ results = explore_module(internal)
+ assert len(results) > 0
+ snapshot("internal_api.txt", "\n".join(results))
diff --git a/tests/_server/templates/test_templates.py b/tests/_server/templates/test_templates.py
index 5cebd44ea7..a6100e572e 100644
--- a/tests/_server/templates/test_templates.py
+++ b/tests/_server/templates/test_templates.py
@@ -64,14 +64,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
def test_notebook_page_template(self) -> None:
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
)
assert self.base_url not in result
@@ -82,14 +82,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
def test_notebook_page_template_no_filename(self) -> None:
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- None,
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=None,
+ mode=self.mode,
)
assert self.base_url not in result
@@ -100,14 +100,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
def test_notebook_page_template_edit_mode(self) -> None:
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- SessionMode.EDIT,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=SessionMode.EDIT,
)
assert self.base_url not in result
@@ -124,14 +124,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
css_file.write_text(css)
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(css_file="custom.css"),
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=_AppConfig(css_file="custom.css"),
+ filename=str(self.filename),
+ mode=self.mode,
)
assert css in result
@@ -155,14 +155,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
head_file.write_text(head)
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- _AppConfig(html_head_file="head.html"),
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=_AppConfig(html_head_file="head.html"),
+ filename=str(self.filename),
+ mode=self.mode,
)
assert head in result.split("</head>", 1)[0]
@@ -183,14 +183,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
config["display"]["custom_css"] = ["custom1.css", "custom2.css"]
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
)
assert css1 in result
@@ -209,14 +209,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
config["display"]["custom_css"] = [str(css_file)]
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
)
assert css in result
@@ -236,14 +236,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
config_overrides["display"] = {"custom_css": ["override.css"]}
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
)
assert css1 in result
@@ -256,14 +256,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
config["display"]["custom_css"] = ["nonexistent.css"]
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
)
assert "nonexistent.css" in result
@@ -275,14 +275,14 @@ class TestNotebookPageTemplate(unittest.TestCase):
asset_url = "https://cdn.example.com/v{version}"
result = templates.notebook_page_template(
- self.html,
- self.base_url,
- self.user_config,
- self.config_overrides,
- self.server_token,
- self.app_config,
- str(self.filename),
- self.mode,
+ html=self.html,
+ base_url=self.base_url,
+ user_config=self.user_config,
+ config_overrides=self.config_overrides,
+ server_token=self.server_token,
+ app_config=self.app_config,
+ filename=str(self.filename),
+ mode=self.mode,
asset_url=asset_url,
)
diff --git a/tests/_server/templates/test_templates_api.py b/tests/_server/templates/test_templates_api.py
new file mode 100644
index 0000000000..9732141ff7
--- /dev/null
+++ b/tests/_server/templates/test_templates_api.py
@@ -0,0 +1,143 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import unittest
+
+from marimo._schemas.session import (
+ VERSION,
+ Cell,
+ DataOutput,
+ NotebookSessionMetadata,
+ NotebookSessionV1,
+)
+from marimo._server.templates.api import (
+ render_notebook,
+ render_static_notebook,
+)
+
+
+class TestRenderNotebook(unittest.TestCase):
+ def setUp(self) -> None:
+ self.code = """
+import marimo as mo
+
+app = mo.App()
+
+def __():
+ import marimo as mo
+ return mo,
+
+def __(mo):
+ mo.md("Hello, World!")
+ return
+
+if __name__ == "__main__":
+ app.run()
+"""
+
+ def test_render_notebook_edit_mode(self) -> None:
+ html = render_notebook(code=self.code, mode="edit")
+ assert "<html" in html
+ assert "</html>" in html
+
+ def test_render_notebook_read_mode(self) -> None:
+ html = render_notebook(code=self.code, mode="read")
+ assert "<html" in html
+
+ def test_render_notebook_with_filename(self) -> None:
+ html = render_notebook(
+ code=self.code, mode="edit", filename="test_notebook.py"
+ )
+ assert "test_notebook.py" in html
+
+ def test_render_notebook_with_config(self) -> None:
+ html = render_notebook(
+ code=self.code,
+ mode="edit",
+ config={"completion": {"activate_on_typing": False}},
+ )
+ assert "activate_on_typing" in html
+
+ def test_render_notebook_with_runtime_config(self) -> None:
+ html = render_notebook(
+ code=self.code,
+ mode="edit",
+ runtime_config=[{"url": "wss://example.com"}],
+ )
+ assert "wss://example.com" in html
+
+ def test_render_notebook_with_custom_css(self) -> None:
+ custom_css = "body { background-color: red; }"
+ html = render_notebook(
+ code=self.code, mode="edit", custom_css=custom_css
+ )
+ assert custom_css in html
+
+
+class TestRenderStaticNotebook(unittest.TestCase):
+ def setUp(self) -> None:
+ self.code = """
+import marimo as mo
+
+app = mo.App()
+
+def __():
+ import marimo as mo
+ return mo,
+
+def __(mo):
+ mo.md("Hello, World!")
+ return
+
+if __name__ == "__main__":
+ app.run()
+"""
+ self.session_snapshot = NotebookSessionV1(
+ version=VERSION,
+ metadata=NotebookSessionMetadata(marimo_version="0.1.0"),
+ cells=[
+ Cell(
+ id="cell1",
+ code_hash="abc123",
+ outputs=[
+ DataOutput(
+ type="data",
+ data={"text/plain": "Hello, World!"},
+ )
+ ],
+ console=[],
+ ),
+ ],
+ )
+
+ def test_render_static_notebook(self) -> None:
+ html = render_static_notebook(
+ code=self.code, session_snapshot=self.session_snapshot
+ )
+ assert "<html" in html
+
+ def test_render_static_notebook_with_filename(self) -> None:
+ html = render_static_notebook(
+ code=self.code,
+ filename="test_notebook.py",
+ session_snapshot=self.session_snapshot,
+ )
+ assert "test_notebook.py" in html
+
+ def test_render_static_notebook_include_code(self) -> None:
+ html_with_code = render_static_notebook(
+ code=self.code,
+ include_code=True,
+ session_snapshot=self.session_snapshot,
+ )
+ html_without_code = render_static_notebook(
+ code=self.code,
+ include_code=False,
+ session_snapshot=self.session_snapshot,
+ )
+ assert "import marimo as mo" in html_with_code
+ assert '<marimo-code hidden=""></marimo-code>' in html_without_code
diff --git a/tests/test_api.py b/tests/test_api.py
index 26ca42246c..4563f57e33 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,57 +1,14 @@
from __future__ import annotations
-import inspect
-from typing import Any, Optional
-
from tests.mocks import snapshotter
+from tests.utils import explore_module
snapshot = snapshotter(__file__)
-def _explore_module(
- module: Any, indent: int = 0, visited: Optional[set[int]] = None
-) -> list[str]:
- """
- Recursively explore a module and print all public exported items.
-
- Args:
- module: The module or object to explore
- indent: Current indentation level (for pretty printing)
- visited: Set[int] = set()
- """
- if visited is None:
- visited = set()
-
- # Skip if we've already visited this object
- if id(module) in visited:
- return []
-
- visited.add(id(module))
-
- results: list[str] = []
- # Get all attributes of the module
- for name, obj in inspect.getmembers(module):
- # Skip private/special attributes (starting with _)
- if name.startswith("_"):
- continue
-
- # Create indentation string
- indent_str = " " * indent
-
- # Print the current item
- results.append(f"{indent_str}{name}")
-
- # Recursively explore if it's a module, class, or other container type
- if inspect.ismodule(obj) and obj.__name__.startswith(module.__name__):
- # Only recurse into submodules of the original module
- results.extend(_explore_module(obj, indent + 1, visited))
-
- return results
-
-
def test_api():
import marimo as mo
- results = _explore_module(mo)
+ results = explore_module(mo)
assert len(results) > 0
snapshot("api.txt", "\n".join(results))
diff --git a/tests/utils.py b/tests/utils.py
index ce09a724e2..9359e86ad0 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -1,7 +1,8 @@
from __future__ import annotations
+import inspect
import time
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Optional
from marimo._messaging.msgspec_encoder import (
asdict,
@@ -36,3 +37,44 @@ def assert_serialize_roundtrip(obj: msgspec.Struct) -> None:
cls = type(obj)
parsed = parse_raw(serialized, cls)
assert asdict(obj) == asdict(parsed), f"{asdict(obj)} != {asdict(parsed)}"
+
+
+def explore_module(
+ module: Any, indent: int = 0, visited: Optional[set[int]] = None
+) -> list[str]:
+ """
+ Recursively explore a module and print all public exported items.
+
+ Args:
+ module: The module or object to explore
+ indent: Current indentation level (for pretty printing)
+ visited: Set[int] = set()
+ """
+ if visited is None:
+ visited = set()
+
+ # Skip if we've already visited this object
+ if id(module) in visited:
+ return []
+
+ visited.add(id(module))
+
+ results: list[str] = []
+ # Get all attributes of the module
+ for name, obj in inspect.getmembers(module):
+ # Skip private/special attributes (starting with _)
+ if name.startswith("_"):
+ continue
+
+ # Create indentation string
+ indent_str = " " * indent
+
+ # Print the current item
+ results.append(f"{indent_str}{name}")
+
+ # Recursively explore if it's a module, class, or other container type
+ if inspect.ismodule(obj) and obj.__name__.startswith(module.__name__):
+ # Only recurse into submodules of the original module
+ results.extend(explore_module(obj, indent + 1, visited))
+
+ return results