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: graceful exit when running as a script (#1217)

Akshay Agrawala2ecafcbb53c
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index 56840a0c96..6ac76dd353 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Literal, final
+from typing import TYPE_CHECKING, Any, Callable, Literal, final
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
@@ -86,13 +86,17 @@ class Html(MIME):
ctx.virtual_file_registry.reference(virtual_filename)
self._virtual_filenames.append(virtual_filename)
- def __del__(self) -> None:
+ # bind the function python_exiting to ensure it still exists at Python
+ # destruction time; for graceful exits when running as a script
+ def __del__(
+ self, _python_exiting: Callable[..., bool] = python_exiting
+ ) -> None:
"""Cleanup side-effects related to initialization.
Subclasses MUST implement a __del__ method that ends by calling
this method.
"""
- if python_exiting():
+ if _python_exiting():
# imports can fail when python is exiting; clean-up
# is not important when exiting anyway
return
@@ -107,7 +111,7 @@ class Html(MIME):
except ContextNotInitializedError:
return
- if ctx is not None:
+ if ctx is not None and ctx.virtual_files_supported:
for f in self._virtual_filenames:
ctx.virtual_file_registry.dereference(f)
diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.py
index 88f696d6e5..782063000d 100644
--- a/marimo/_plugins/stateless/status/_progress.py
+++ b/marimo/_plugins/stateless/status/_progress.py
@@ -3,13 +3,21 @@ from __future__ import annotations
import contextlib
import time
-from typing import TYPE_CHECKING, Iterable, Iterator, Optional, TypeVar
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ Iterable,
+ Iterator,
+ Optional,
+ TypeVar,
+)
import marimo._runtime.output._output as output
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import build_stateless_plugin
from marimo._utils.debounce import debounce
+from marimo._utils.exiting import python_exiting
if TYPE_CHECKING:
from collections.abc import Collection
@@ -45,7 +53,12 @@ class _Progress(Html):
self.start_time = time.time()
super().__init__(self._get_text())
- def __del__(self) -> None:
+ def __del__(
+ self, _python_exiting: Callable[..., bool] = python_exiting
+ ) -> None:
+ if _python_exiting():
+ return
+
super().__del__()
def update_progress(
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index f04aedac3c..1cc614e390 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -20,11 +20,9 @@ from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType, build_ui_plugin
from marimo._plugins.ui._core import ids
-from marimo._runtime.context import (
- ContextNotInitializedError,
- get_context,
-)
+from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._runtime.functions import Function
+from marimo._utils.exiting import python_exiting
if TYPE_CHECKING:
from marimo._plugins.ui._impl.input import form as form_plugin
@@ -229,7 +227,16 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
except ContextNotInitializedError:
pass
- def __del__(self) -> None:
+ # bind the function python_exiting to ensure it still exists at Python
+ # destruction time; for graceful exits when running as a script
+ def __del__(
+ self, _python_exiting: Callable[..., bool] = python_exiting
+ ) -> None:
+ if _python_exiting():
+ # imports can fail when python is exiting; clean-up
+ # is not important when exiting anyway
+ return
+
try:
ctx = get_context()
ctx.ui_element_registry.delete(self._id, id(self))
diff --git a/marimo/_utils/exiting.py b/marimo/_utils/exiting.py
index 77c141b194..1380cd6256 100644
--- a/marimo/_utils/exiting.py
+++ b/marimo/_utils/exiting.py
@@ -11,8 +11,10 @@ class Exiting:
_PYTHON_EXITING = Exiting()
-def python_exiting() -> bool:
- return _PYTHON_EXITING.value
+# bind the global _PYTHON_EXITING to ensure it still exists
+# at Python destruction time; for graceful exits when running as a script
+def python_exiting(_exiting: Exiting = _PYTHON_EXITING) -> bool:
+ return _exiting.value
def _exit() -> None:
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index e02b8297b9..97923c3ec3 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -2,12 +2,17 @@
from __future__ import annotations
import asyncio
+import inspect
import subprocess
from os import path
+from typing import TYPE_CHECKING
from tests._server.templates.utils import normalize_index_html
from tests.mocks import snapshotter
+if TYPE_CHECKING:
+ import pathlib
+
snapshot = snapshotter(__file__)
@@ -123,6 +128,95 @@ class TestExportHTML:
break
+class TestExportHtmlSmokeTests:
+ def assert_not_errored(
+ self, p: subprocess.CompletedProcess[bytes]
+ ) -> None:
+ assert p.returncode == 0
+ assert not any(
+ line.startswith("Traceback")
+ for line in p.stderr.decode().splitlines()
+ )
+ assert not any(
+ line.startswith("Traceback")
+ for line in p.stdout.decode().splitlines()
+ )
+
+ def test_export_intro_tutorial(self, tmp_path: pathlib.Path) -> None:
+ from marimo._tutorials import intro
+
+ file = tmp_path / "intro.py"
+ out = tmp_path / "out.html"
+ file.write_text(inspect.getsource(intro))
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+ def test_export_ui_tutorial(self, tmp_path: pathlib.Path) -> None:
+ from marimo._tutorials import ui as mod
+
+ file = tmp_path / "mod.py"
+ file.write_text(inspect.getsource(mod))
+ out = tmp_path / "out.html"
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+ def test_export_dataflow_tutorial(self, tmp_path: pathlib.Path) -> None:
+ from marimo._tutorials import dataflow as mod
+
+ file = tmp_path / "mod.py"
+ file.write_text(inspect.getsource(mod))
+ out = tmp_path / "out.html"
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+ def test_export_layout_tutorial(self, tmp_path: pathlib.Path) -> None:
+ from marimo._tutorials import layout as mod
+
+ file = tmp_path / "mod.py"
+ file.write_text(inspect.getsource(mod))
+ out = tmp_path / "out.html"
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+ def test_export_plots_tutorial(self, tmp_path: pathlib.Path) -> None:
+ from marimo._tutorials import plots
+
+ file = tmp_path / "plots.py"
+ file.write_text(inspect.getsource(plots))
+ out = tmp_path / "out.html"
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+ def test_export_marimo_for_jupyter_users(
+ self, tmp_path: pathlib.Path
+ ) -> None:
+ from marimo._tutorials import marimo_for_jupyter_users as mod
+
+ file = tmp_path / "mod.py"
+ file.write_text(inspect.getsource(mod))
+ out = tmp_path / "out.html"
+ p = subprocess.run(
+ ["marimo", "export", "html", str(file), "-o", str(out)],
+ capture_output=True,
+ )
+ self.assert_not_errored(p)
+
+
class TestExportScript:
@staticmethod
def test_export_script(temp_marimo_file: str) -> None: