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: stop script mode from importing matplotlib on startup (#11590)

Dylan Madisettieae848c427af
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 1c1246c1af..0a97881da9 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -45,6 +45,15 @@ if TYPE_CHECKING:
from marimo._save.cache import CacheState
+def _close_matplotlib_figures() -> None:
+ """Close pyplot figures after each cell so the next one starts fresh."""
+ if not DependencyManager.imported("matplotlib.pyplot"):
+ return
+ from marimo._output.mpl import close_figures
+
+ close_figures()
+
+
class AppScriptRunner:
"""Runs an app in a script context."""
@@ -313,11 +322,9 @@ class AppScriptRunner:
)
self._evaluator.lifecycles = [self._cache]
- post_execute_hooks: list[Callable[[], Any]] = []
- if DependencyManager.matplotlib.has():
- from marimo._output.mpl import close_figures
-
- post_execute_hooks.append(close_figures)
+ post_execute_hooks: list[Callable[[], Any]] = [
+ _close_matplotlib_figures
+ ]
if is_async:
outputs, defs = run_coroutine_blocking(
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index cc25876284..341282b9a8 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -1385,6 +1385,43 @@ def test_cli_args(tmp_path: pathlib.Path) -> None:
assert "value2" in output
+ condition=not DependencyManager.matplotlib.has(),
+ reason="requires matplotlib",
+)
+def test_script_run_does_not_import_matplotlib(
+ tmp_path: pathlib.Path,
+) -> None:
+ """A script run leaves matplotlib alone until a cell imports it.
+
+ Loading it costs a font-cache build on a fresh machine, which can
+ take longer than the notebook itself.
+ """
+ py_file = tmp_path / "no_mpl_script.py"
+ content = """
+ import marimo
+ app = marimo.App()
+
+ @app.cell
+ def __():
+ import sys
+ print("matplotlib" in sys.modules)
+ return
+
+ if __name__ == "__main__":
+ app.run()
+ """
+ py_file.write_text(textwrap.dedent(content))
+ p = subprocess.run(
+ [sys.executable, str(py_file)],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+ assert p.returncode == 0, p.stderr
+ assert p.stdout.strip() == "False"
+
+
# TODO(akshayka): Many of the app composition and embedding tests are flaky in
# CI. This suggests either cross-test state pollution or a bug in the
# underlying implementation. These bugs are not high priority to fix, so