Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improvements for running as a script #973

Merged
merged 3 commits into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions marimo/_ast/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,15 @@ async def _run_async(self) -> tuple[Sequence[Any], dict[str, Any]]:
)

def run(self) -> tuple[Sequence[Any], dict[str, Any]]:
# formatters aren't automatically registered when running as a script
from marimo._output.formatters.formatters import (
register_formatters,
)
from marimo._output.formatting import FORMATTERS

if not FORMATTERS:
register_formatters()

return asyncio.run(self._run_async())

async def _run_cell_async(
Expand Down
10 changes: 8 additions & 2 deletions marimo/_output/hypertext.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._output.utils import flatten_string
from marimo._utils.exiting import python_exiting

if TYPE_CHECKING:
from marimo._plugins.core.web_component import JSONType
Expand Down Expand Up @@ -91,6 +92,10 @@ def __del__(self) -> None:
Subclasses MUST implement a __del__ method that ends by calling
this method.
"""
if python_exiting():
# imports can fail when python is exiting; clean-up
# is not important when exiting anyway
return

from marimo._runtime.context import (
ContextNotInitializedError,
Expand All @@ -102,8 +107,9 @@ def __del__(self) -> None:
except ContextNotInitializedError:
return

for f in self._virtual_filenames:
ctx.virtual_file_registry.dereference(f)
if ctx is not None:
for f in self._virtual_filenames:
ctx.virtual_file_registry.dereference(f)

@property
def text(self) -> str:
Expand Down
22 changes: 22 additions & 0 deletions marimo/_utils/exiting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Copyright 2024 Marimo. All rights reserved.
import atexit
from dataclasses import dataclass


@dataclass
class Exiting:
value: bool = False


_PYTHON_EXITING = Exiting()


def python_exiting() -> bool:
return _PYTHON_EXITING.value


def _exit() -> None:
_PYTHON_EXITING.value = True


atexit.register(_exit)
Loading