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.

fix(lazy): resolve `mo.lazy` eagerly in non-interactive exports (#9644)

Myles Scolnickcbde228871b0
diff --git a/marimo/_plugins/stateless/lazy.py b/marimo/_plugins/stateless/lazy.py
index 2fb84278e8..9cb37c97d4 100644
--- a/marimo/_plugins/stateless/lazy.py
+++ b/marimo/_plugins/stateless/lazy.py
@@ -3,9 +3,11 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Final
+from typing import TYPE_CHECKING, Any, Final
+from marimo import _loggers
from marimo._output.formatting import as_html
+from marimo._output.hypertext import Html, is_non_interactive
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.functions import EmptyArgs, Function
@@ -13,12 +15,18 @@ from marimo._runtime.functions import EmptyArgs, Function
if TYPE_CHECKING:
from collections.abc import Callable, Coroutine
+LOGGER = _loggers.marimo_logger()
+
@dataclass
class LoadResponse:
html: str
+def _is_lazy_callable(element: object) -> bool:
+ return callable(element) and not isinstance(element, UIElement)
+
+
@mddoc
class lazy(UIElement[bool, bool]):
"""Lazy load a component until it is visible.
@@ -33,6 +41,14 @@ class lazy(UIElement[bool, bool]):
Using a function is useful when the item to render is
the result of a database query or some other expensive operation.
+ Note:
+ In non-interactive contexts (ipynb and PDF exports), `mo.lazy`
+ renders its element eagerly and returns the resolved HTML
+ directly, since no kernel is available to invoke the lazy load
+ function. Async elements cannot be resolved from a synchronous
+ constructor; they fall back to the lazy widget. HTML export
+ keeps the lazy widget as-is.
+
Examples:
Create a lazy-loaded tab:
```python
@@ -63,6 +79,19 @@ class lazy(UIElement[bool, bool]):
_name: Final[str] = "marimo-lazy"
+ def __new__(
+ cls,
+ element: Callable[[], object]
+ | object
+ | Callable[[], Coroutine[None, None, object]],
+ show_loading_indicator: bool = False, # noqa: ARG004
+ ) -> Any:
+ if is_non_interactive():
+ resolved = _resolve_eagerly(element)
+ if resolved is not None:
+ return resolved
+ return super().__new__(cls)
+
def __init__(
self,
element: Callable[[], object]
@@ -93,12 +122,34 @@ class lazy(UIElement[bool, bool]):
return value
async def _load(self, _args: EmptyArgs) -> LoadResponse:
- if callable(self._element) and not isinstance(
- self._element, UIElement
- ):
- el = self._element()
- if asyncio.iscoroutine(el):
- el = await el
- return LoadResponse(html=as_html(el).text)
+ if _is_lazy_callable(self._element):
+ el = self._element() # type: ignore[operator]
else:
- return LoadResponse(html=as_html(self._element).text)
+ el = self._element
+ if asyncio.iscoroutine(el):
+ el = await el
+ return LoadResponse(html=as_html(el).text)
+
+
+def _resolve_eagerly(element: object) -> Html | None:
+ if asyncio.iscoroutine(element):
+ element.close()
+ return None
+
+ if not _is_lazy_callable(element):
+ return as_html(element)
+
+ if asyncio.iscoroutinefunction(element):
+ return None
+
+ try:
+ result = element() # type: ignore[operator]
+ except Exception as e:
+ LOGGER.debug("mo.lazy: failed to resolve element for export: %s", e)
+ return None
+
+ if asyncio.iscoroutine(result):
+ result.close()
+ return None
+
+ return as_html(result)
diff --git a/marimo/_smoke_tests/pdf_export/lazy_outputs.py b/marimo/_smoke_tests/pdf_export/lazy_outputs.py
new file mode 100644
index 0000000000..bde280c698
--- /dev/null
+++ b/marimo/_smoke_tests/pdf_export/lazy_outputs.py
@@ -0,0 +1,62 @@
+import marimo
+
+__generated_with = "0.23.5"
+app = marimo.App()
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+def _(mo):
+ mo.md("# `mo.lazy` export smoke test")
+ return
+
+
+def _(mo):
+ mo.md("## 1) Eager value (non-callable)")
+ return
+
+
+def _(mo):
+ mo.lazy("EAGER_VALUE_MARKER")
+ return
+
+
+def _(mo):
+ mo.md("## 2) Sync function")
+ return
+
+
+def _(mo):
+ def make_sync():
+ return "SYNC_FUNCTION_MARKER"
+
+ mo.lazy(make_sync)
+ return
+
+
+def _(mo):
+ mo.md("## 3) Async function")
+ return
+
+
+def _(mo):
+ async def make_async():
+ return "ASYNC_FUNCTION_MARKER"
+
+ mo.lazy(make_async)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/stateless/test_lazy.py b/tests/_plugins/stateless/test_lazy.py
index e8ea0c9db2..dfa640aefc 100644
--- a/tests/_plugins/stateless/test_lazy.py
+++ b/tests/_plugins/stateless/test_lazy.py
@@ -1,8 +1,13 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import textwrap
from typing import Any
+import pytest
+
+import marimo as mo
+from marimo._output.hypertext import patch_html_for_non_interactive_output
from marimo._runtime.context import get_context
from marimo._runtime.context.types import RuntimeContext
from marimo._runtime.functions import Function
@@ -18,56 +23,134 @@ def get_only_function() -> Function[Any, Any]:
return next(iter(first_namespace.functions.values()))
-async def test_lazy(k: Kernel, exec_req: ExecReqProvider) -> None:
- await k.run(
- [
- exec_req.get(
- """
- import marimo as mo
- lazy = mo.lazy(42)
- """
- ),
- ]
- )
- first_function = get_only_function()
- assert first_function.name == "load"
- res = await first_function({})
- assert res.html == "<span>42</span>"
+_LAZY_PROGRAMS = {
+ "value": "lazy = mo.lazy(42)",
+ "sync_callable": "lazy = mo.lazy(lambda: 42)",
+ "async_callable": textwrap.dedent(
+ """
+ async def get_value():
+ return 42
+ lazy = mo.lazy(get_value)
+ """
+ ),
+}
-async def test_lazy_function(k: Kernel, exec_req: ExecReqProvider) -> None:
- await k.run(
- [
- exec_req.get(
- """
- import marimo as mo
- lazy = mo.lazy(lambda: 42)
- """
- ),
- ]
- )
- first_function = get_only_function()
- assert first_function.name == "load"
- res = await first_function({})
+ "program", _LAZY_PROGRAMS.values(), ids=list(_LAZY_PROGRAMS)
+)
+async def test_lazy_load_function_resolves(
+ k: Kernel, exec_req: ExecReqProvider, program: str
+) -> None:
+ await k.run([exec_req.get(f"import marimo as mo\n{program}")])
+ fn = get_only_function()
+ assert fn.name == "load"
+ res = await fn({})
assert res.html == "<span>42</span>"
-async def test_lazy_async_function(
+async def test_lazy_is_lazy_in_interactive_context(
k: Kernel, exec_req: ExecReqProvider
) -> None:
await k.run(
[
exec_req.get(
- """
- import marimo as mo
- async def get_value():
- return 42
- lazy = mo.lazy(get_value)
- """
+ textwrap.dedent(
+ """
+ import marimo as mo
+ calls = 0
+ def get_value():
+ global calls
+ calls += 1
+ return 42
+ lazy = mo.lazy(get_value)
+ """
+ )
),
]
)
- first_function = get_only_function()
- assert first_function.name == "load"
- res = await first_function({})
- assert res.html == "<span>42</span>"
+ assert k.globals["calls"] == 0
+ lazy_obj = k.globals["lazy"]
+ assert "marimo-lazy" in lazy_obj.text
+ assert "<span>42</span>" not in lazy_obj.text
+
+
+ ("element_factory", "expected_html"),
+ [
+ pytest.param(lambda: 42, "<span>42</span>", id="value"),
+ pytest.param(
+ lambda: lambda: 42, "<span>42</span>", id="sync_callable"
+ ),
+ pytest.param(
+ lambda: mo.md("# heading"), "<h1", id="ui_element_passthrough"
+ ),
+ ],
+)
+def test_lazy_resolves_eagerly_in_non_interactive_context(
+ element_factory: Any, expected_html: str
+) -> None:
+ with patch_html_for_non_interactive_output():
+ result = mo.lazy(element_factory())
+ assert not isinstance(result, mo.lazy)
+ assert expected_html in result.text
+
+
+def test_lazy_sync_callable_is_invoked_exactly_once() -> None:
+ calls = 0
+
+ def get_value() -> int:
+ nonlocal calls
+ calls += 1
+ return 42
+
+ with patch_html_for_non_interactive_output():
+ result = mo.lazy(get_value)
+ assert calls == 1
+ assert "<span>42</span>" in result.text
+
+
+def _async_def() -> Any:
+ async def get_value() -> int:
+ return 42
+
+ return get_value
+
+
+def _coroutine_returning_lambda() -> Any:
+ async def _inner() -> int:
+ return 42
+
+ return lambda: _inner()
+
+
+def _raw_coroutine() -> Any:
+ async def _inner() -> int:
+ return 42
+
+ return _inner()
+
+
+ "make_element",
+ [
+ pytest.param(_async_def, id="async_callable"),
+ pytest.param(_coroutine_returning_lambda, id="coroutine_return"),
+ pytest.param(_raw_coroutine, id="raw_coroutine"),
+ ],
+)
+def test_lazy_falls_back_to_widget_for_async_in_non_interactive_context(
+ make_element: Any,
+) -> None:
+ with patch_html_for_non_interactive_output():
+ result = mo.lazy(make_element())
+ assert isinstance(result, mo.lazy)
+
+
+def test_lazy_falls_back_to_widget_when_sync_callable_raises() -> None:
+ def boom() -> int:
+ raise RuntimeError("nope")
+
+ with patch_html_for_non_interactive_output():
+ result = mo.lazy(boom)
+ assert isinstance(result, mo.lazy)
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 6820ac727a..bf5def8451 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -5,6 +5,7 @@ import base64
import json
import pathlib
import sys
+import textwrap
from typing import TYPE_CHECKING, Any
from unittest.mock import ANY, AsyncMock, MagicMock, patch
@@ -20,6 +21,8 @@ from marimo._messaging.msgspec_encoder import encode_json_str
from marimo._messaging.notification import CellNotification
from marimo._server.export import (
export_as_wasm,
+ run_app_then_export_as_html,
+ run_app_then_export_as_ipynb,
run_app_then_export_as_pdf,
run_app_until_completion,
)
@@ -639,6 +642,108 @@ def test_export_as_html_with_error_outputs(session_view: SessionView) -> None:
assert "Test error" in html or "ValueError" in html
+def _write_lazy_notebook(path: Path, lazy_arg: str) -> None:
+ path.write_text(
+ textwrap.dedent(
+ f"""
+ import marimo
+
+ app = marimo.App()
+
+
+ @app.cell
+ def _():
+ import marimo as mo
+
+ def _make_async():
+ async def inner():
+ return "ASYNC_RESULT"
+ return inner
+
+ mo.lazy({lazy_arg})
+ return ()
+
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ )
+ )
+
+
+ not DependencyManager.nbformat.has(), reason="nbformat not installed"
+)
+ ("lazy_arg", "expected_marker", "should_resolve"),
+ [
+ pytest.param('"EAGER_VALUE"', "EAGER_VALUE", True, id="eager_value"),
+ pytest.param(
+ 'lambda: "SYNC_RESULT"', "SYNC_RESULT", True, id="sync_callable"
+ ),
+ pytest.param(
+ "_make_async()", "ASYNC_RESULT", False, id="async_callable"
+ ),
+ ],
+)
+async def test_run_app_then_export_as_ipynb_resolves_lazy(
+ tmp_path: Path,
+ lazy_arg: str,
+ expected_marker: str,
+ should_resolve: bool,
+) -> None:
+ """Regression test for https://github.com/marimo-team/marimo/issues/9624.
+
+ Non-interactive exports (ipynb, PDF) resolve sync `mo.lazy` content
+ eagerly. Async elements can't be awaited from `__new__` and stay as
+ placeholders.
+ """
+ notebook = tmp_path / "lazy_notebook.py"
+ _write_lazy_notebook(notebook, lazy_arg)
+
+ result = await run_app_then_export_as_ipynb(
+ filepath=MarimoPath(str(notebook)),
+ sort_mode="top-down",
+ cli_args={},
+ argv=[],
+ )
+
+ # The rendered HTML is wrapped in <span> by as_html; the raw marker
+ # alone appears in the cell source regardless, so check the wrapped
+ # form to confirm resolution.
+ rendered = f"<span>{expected_marker}</span>"
+ if should_resolve:
+ assert rendered in result.contents
+ assert "marimo-lazy" not in result.contents
+ else:
+ assert "marimo-lazy" in result.contents
+ assert rendered not in result.contents
+
+
+async def test_run_app_then_export_as_html_keeps_lazy_placeholder(
+ tmp_path: Path,
+) -> None:
+ """HTML export ships interactive widgets and leaves `mo.lazy` as a placeholder.
+
+ Static HTML exports don't resolve `mo.lazy` because the global
+ `is_non_interactive` flag would also switch tables/altair/plotly/etc.
+ to non-interactive fallbacks. A lazy-specific resolution path can be
+ added later as a follow-up.
+ """
+ notebook = tmp_path / "lazy_notebook.py"
+ _write_lazy_notebook(notebook, 'lambda: "SYNC_RESULT"')
+
+ result = await run_app_then_export_as_html(
+ path=MarimoPath(str(notebook)),
+ include_code=False,
+ cli_args={},
+ argv=[],
+ )
+
+ assert "marimo-lazy" in result.contents
+ assert "SYNC_RESULT" not in result.contents
+
+
def test_export_as_html_code_hash_consistency(
session_view: SessionView,
) -> None: