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: more robust app composition (#1784)

Akshay Agrawalcaae3252cb40
diff --git a/docs/api/app.md b/docs/api/app.md
new file mode 100644
index 0000000000..f9d4f089fa
--- /dev/null
+++ b/docs/api/app.md
@@ -0,0 +1,7 @@
+# Cell
+
+```{eval-rst}
+.. autoclass:: marimo.App
+
+ .. automethod:: marimo.App.embed
+```
diff --git a/docs/api/index.md b/docs/api/index.md
index 121d1832ea..a70d26ebf5 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -18,6 +18,7 @@
query_params
cli_args
state
+ app
cell
miscellaneous
```
@@ -45,5 +46,6 @@ Use the marimo library in marimo notebooks (`import marimo as mo`) to
| {doc}`query_params` | Access and set query parameters with `mo.query_params` |
| {doc}`cli_args` | Access command-line arguments with `mo.cli_args` |
| {doc}`state` | Synchronize multiple UI elements with `mo.state` |
+| {doc}`app` | Embed notebooks in other notebooks |
| {doc}`cell` | Run cells defined in another notebook |
| {doc}`miscellaneous` | Miscellaneous utilities |
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index b08e3f1a89..30c044cbc7 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1,7 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-import asyncio
import random
import string
from dataclasses import asdict, dataclass
@@ -17,11 +16,7 @@ from typing import (
from uuid import uuid4
from marimo import _loggers
-from marimo._ast.cell import (
- Cell,
- CellConfig,
- CellId_t,
-)
+from marimo._ast.cell import Cell, CellConfig, CellId_t
from marimo._ast.compiler import cell_factory
from marimo._ast.errors import (
CycleError,
@@ -30,18 +25,17 @@ from marimo._ast.errors import (
UnparsableError,
)
from marimo._config.config import WidthType
-from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.mimetypes import KnownMimeType
-from marimo._messaging.types import NoopStream
+from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
-from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime import dataflow
-from marimo._runtime.context.types import get_context
-from marimo._runtime.executor import (
- execute_cell,
- execute_cell_async,
+from marimo._runtime.app.kernel_runner import AppKernelRunner
+from marimo._runtime.app.script_runner import AppScriptRunner
+from marimo._runtime.context.types import (
+ get_context,
+ runtime_context_installed,
)
-from marimo._runtime.patches import patch_main_module_context
+from marimo._runtime.requests import SetUIElementValueRequest
if TYPE_CHECKING:
from collections.abc import Sequence
@@ -127,14 +121,18 @@ class _Namespace(Mapping[str, object]):
return tree(self._dict)._mime_()
+@dataclass
+class AppEmbedResult:
+ output: Html
+ defs: Mapping[str, object]
+
+
@mddoc
class App:
- """A marimo app.
+ """A marimo notebook.
- A marimo app is a dataflow graph, with each node computing a Python
+ A marimo notebook is a dataflow graph, with each node computing a Python
function.
-
- This class has no public API, but this may change in the future.
"""
def __init__(self, **kwargs: Any) -> None:
@@ -143,7 +141,15 @@ class App:
# a TypeError.
self._config = _AppConfig.from_untrusted_dict(kwargs)
- self._cell_manager = CellManager()
+ if runtime_context_installed():
+ # nested applications get a unique cell prefix to disambiguate
+ # their graph from other graphs
+ get_context()
+ cell_prefix = str(uuid4())
+ else:
+ cell_prefix = ""
+
+ self._cell_manager = CellManager(prefix=cell_prefix)
self._graph = dataflow.DirectedGraph()
self._execution_context: ExecutionContext | None = None
self._runner = dataflow.Runner(self._graph)
@@ -151,10 +157,7 @@ class App:
self._unparsable = False
self._initialized = False
- self._app_uuid = str(uuid4())
- self._pending_ui_element_updates: list[UIElement[Any, Any]] = []
- self._cached_outputs: dict[CellId_t, Any] | None = None
- self._cached_defs: Mapping[str, object] | None = None
+ self._app_kernel_runner: AppKernelRunner | None = None
def cell(
self,
@@ -209,7 +212,7 @@ class App:
def _maybe_initialize(self) -> None:
if self._unparsable:
- raise RuntimeError(
+ raise UnparsableError(
"This notebook has cells with syntax errors, "
"so it cannot be initialized."
)
@@ -247,201 +250,32 @@ class App:
finally:
self._initialized = True
+ def _get_kernel_runner(self) -> AppKernelRunner:
+ if self._app_kernel_runner is None:
+ self._app_kernel_runner = AppKernelRunner(InternalApp(self))
+ return self._app_kernel_runner
+
def _flatten_outputs(self, outputs: dict[CellId_t, Any]) -> Sequence[Any]:
return tuple(
outputs[cid]
for cid in self._cell_manager.valid_cell_ids()
- if not self._graph.is_disabled(cid)
+ if not self._graph.is_disabled(cid) and cid in outputs
)
- def _outputs_and_defs(
- self, outputs: dict[CellId_t, Any], glbls: dict[str, Any]
- ) -> tuple[Sequence[Any], _Namespace]:
- # Returns
- # - the outputs, sorted in the order that cells were added to the
- # graph
- # - dict of defs -> values
-
- # Cache the outputs keyed by cell ID
- self._cached_outputs = outputs
-
- # Cache only def values, not all of glbls
- # omit defs that were never defined at runtime, eg due to
- # conditional definitions like
- #
- # if cond:
- # x = 0
- self._cached_defs = _Namespace(
+ def _globals_to_defs(self, glbls: dict[str, Any]) -> _Namespace:
+ return _Namespace(
dictionary={
name: glbls[name] for name in self._defs if name in glbls
},
owner=self,
)
- return (self._flatten_outputs(outputs), self._cached_defs)
-
- # should be kept synchronized with _run_async
- # TODO(akshayka): DRY these functions
- def _run_sync(
- self,
- post_execute_hooks: list[Callable[..., Any]],
- cells_to_run: set[CellId_t] | None,
- ) -> tuple[Sequence[Any], Mapping[str, Any]]:
- # No need to provide `file`, `input_override` here, since this
- # function is only called when running as a script
- with patch_main_module_context() as module:
- glbls = module.__dict__
- # Execute cells and collect outputs
- outputs: dict[CellId_t, Any] = {}
- for cid in self._execution_order:
- cell = self._cell_manager.cell_data_at(cid).cell
- if cell is None:
- continue
-
- if cells_to_run is not None and cid not in cells_to_run:
- assert self._cached_defs is not None
- assert self._cached_outputs is not None
- outputs[cid] = self._cached_outputs[cid]
- glbls = {
- **glbls,
- **{
- name: self._cached_defs[name]
- for name in cell.defs
- if name in self._cached_defs
- },
- }
- continue
-
- if cell is not None and not self._graph.is_disabled(cid):
- with get_context().with_cell_id(
- self._app_uuid + "-" + cid
- ):
- output = execute_cell(cell._cell, glbls, self._graph)
- for hook in post_execute_hooks:
- hook()
- outputs[cid] = output
- return self._outputs_and_defs(outputs, glbls)
-
- async def _run_async(
+ def run(
self,
- post_execute_hooks: list[Callable[..., Any]],
- cells_to_run: set[CellId_t] | None = None,
) -> tuple[Sequence[Any], Mapping[str, Any]]:
- # No need to provide `file`, `input_override` here, since this
- # function is only called when running as a script
- with patch_main_module_context() as module:
- glbls = module.__dict__
- # Execute cells and collect outputs
- outputs: dict[CellId_t, Any] = {}
- for cid in self._execution_order:
- cell = self._cell_manager.cell_data_at(cid).cell
- if cell is None:
- continue
-
- if cells_to_run is not None and cid not in cells_to_run:
- assert self._cached_defs is not None
- assert self._cached_outputs is not None
- outputs[cid] = self._cached_outputs[cid]
- glbls = {
- **glbls,
- **{
- name: self._cached_defs[name]
- for name in cell.defs
- if name in self._cached_defs
- },
- }
- continue
-
- if cell is not None and not self._graph.is_disabled(cid):
- with get_context().with_cell_id(
- self._app_uuid + "-" + cid
- ):
- output = await execute_cell_async(
- cell._cell, glbls, self._graph
- )
- for hook in post_execute_hooks:
- hook()
- outputs[cid] = output
-
- return self._outputs_and_defs(outputs, glbls)
-
- def _run_internal(
- self, cells_to_run: set[CellId_t] | None = None
- ) -> tuple[Sequence[Any], Mapping[str, Any]]:
- from marimo._runtime.context.script_context import (
- initialize_script_context,
- )
- from marimo._runtime.context.types import (
- runtime_context_installed,
- teardown_context,
- )
-
- if self._unparsable:
- raise UnparsableError(
- "This app can't be run because it has unparsable cells."
- )
self._maybe_initialize()
-
- is_async = False
- for cell in self._cell_manager.cells():
- if cell is None:
- raise RuntimeError(
- "Unparsable cell encountered. This is a bug in marimo, "
- "please raise an issue."
- )
-
- if cell._is_coroutine():
- is_async = True
- break
-
- installed_script_context = False
- try:
- if not runtime_context_installed():
- initialize_script_context(
- app=InternalApp(self), stream=NoopStream()
- )
- installed_script_context = True
-
- # 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()
-
- post_execute_hooks = []
- if DependencyManager.has_matplotlib():
- from marimo._output.mpl import close_figures
-
- post_execute_hooks.append(close_figures)
-
- # Provide a unique identifier for UI element prefixes so UI
- # elements for an app don't get removed from the frontend on re-run
- #
- # TODO(akshayka): Do repeated runs cause a leak on the frontend?
- with get_context().provide_ui_ids(prefix=str(uuid4())):
- if is_async:
- return asyncio.run(
- self._run_async(
- post_execute_hooks=post_execute_hooks,
- cells_to_run=cells_to_run,
- )
- )
- else:
- return self._run_sync(
- post_execute_hooks=post_execute_hooks,
- cells_to_run=cells_to_run,
- )
-
- finally:
- if installed_script_context:
- teardown_context()
-
- def run(self) -> tuple[Sequence[Any], Mapping[str, Any]]:
- return self._run_internal()
+ outputs, glbls = AppScriptRunner(InternalApp(self)).run()
+ return (self._flatten_outputs(outputs), self._globals_to_defs(glbls))
async def _run_cell_async(
self, cell: Cell, kwargs: dict[str, Any]
@@ -459,43 +293,91 @@ class App:
output, defs = self._runner.run_cell_sync(cell._cell.cell_id, kwargs)
return output, _Namespace(defs, owner=self)
- def _register_ui_element_update(self, value: UIElement[Any, Any]) -> None:
- if value not in self._pending_ui_element_updates:
- self._pending_ui_element_updates.append(value)
+ async def _set_ui_element_value(
+ self, request: SetUIElementValueRequest
+ ) -> bool:
+ app_kernel_runner = self._get_kernel_runner()
+ return await app_kernel_runner.set_ui_element_value(request)
- def _mime_(self) -> tuple[KnownMimeType, str]:
+ @mddoc
+ async def embed(self) -> AppEmbedResult:
+ """Embed a notebook into another notebook.
+
+ The `embed` method lets you embed the output of a notebook
+ into another notebook and access the values of its variables.
+
+ **Example.**
+
+ ```python
+ from my_notebook import app
+ ```
+
+ ```python
+ # execute the notebook
+ result = await app.embed()
+ ```
+
+ ```python
+ # view the notebook's visual output
+ result.output
+ ```
+
+ ```python
+ # access the notebook's defined variables
+ result.defs
+ ```
+
+ Running `await app.embed()` executes the notebook and results an object
+ encapsulating the notebook visual output and its definitions.
+
+ Embedded notebook outputs are interactive: when you interact with
+ UI elements in an embedded notebook's output, any cell referring
+ to the `app` object is marked for execution, and its internal state
+ is automatically updated. This lets you notebooks as building blocks or
+ components to create higher-level notebooks.
+
+ Multiple levels of nesting are supported: it's possible to embed a
+ notebook that in turn embeds another notebook, and marimo will do the
+ right thing.
+
+ **Returns.**
+
+ - An object `result` with two attributes: `result.output` (visual
+ output of the notebook) and `result.defs` (a dictionary mapping
+ variable names defined by the notebook to their values).
+ """
from marimo._plugins.stateless.flex import vstack
+ from marimo._runtime.context.utils import running_in_notebook
+
+ self._maybe_initialize()
- if self._pending_ui_element_updates and self._cached_defs:
- updated_names: set[str] = set()
- defining_cells = set()
- while self._pending_ui_element_updates:
- element = self._pending_ui_element_updates.pop()
- for name, value in self._cached_defs.items():
- if value is element:
- updated_names.add(name)
- defining_cells |= self._graph.get_defining_cells(name)
- break
- descendants = dataflow.transitive_closure(
- self._graph,
- defining_cells,
- inclusive=False,
+ if running_in_notebook():
+ app_kernel_runner = self._get_kernel_runner()
+ if not app_kernel_runner.outputs:
+ outputs, glbls = await app_kernel_runner.run(
+ set(self._execution_order)
+ )
+ else:
+ outputs, glbls = (
+ app_kernel_runner.outputs,
+ app_kernel_runner.globals,
+ )
+ return AppEmbedResult(
+ output=vstack(
+ [
+ o
+ for o in self._flatten_outputs(outputs)
+ if o is not None
+ ]
+ ),
+ defs=self._globals_to_defs(glbls),
+ )
+ else:
+ flat_outputs, defs = self.run()
+ return AppEmbedResult(
+ output=vstack([o for o in flat_outputs if o is not None]),
+ defs=defs,
)
- self._run_internal(cells_to_run=descendants)
- elif self._cached_outputs is None:
- self.run()
-
- assert self._cached_outputs is not None
- return (
- "text/html",
- vstack(
- [
- o
- for o in self._flatten_outputs(self._cached_outputs)
- if o is not None
- ]
- ).text,
- )
class CellManager:
@@ -506,14 +388,17 @@ class CellManager:
provides methods to access them.
"""
- def __init__(self) -> None:
+ def __init__(self, prefix: str = "") -> None:
self._cell_data: dict[CellId_t, CellData] = {}
+ self.prefix = prefix
self.unparsable = False
self.random_seed = random.Random(42)
def create_cell_id(self) -> CellId_t:
# 4 random letters
- return "".join(self.random_seed.choices(string.ascii_letters, k=4))
+ return self.prefix + "".join(
+ self.random_seed.choices(string.ascii_letters, k=4)
+ )
def cell_decorator(
self,
@@ -675,6 +560,11 @@ class InternalApp:
self._app._maybe_initialize()
return self._app._graph
+ @property
+ def execution_order(self) -> list[CellId_t]:
+ self._app._maybe_initialize()
+ return self._app._execution_order
+
@property
def execution_context(self) -> ExecutionContext | None:
return self._app._execution_context
@@ -728,3 +618,8 @@ class InternalApp:
self, cell: Cell, kwargs: dict[str, Any]
) -> tuple[Any, _Namespace]:
return self._app._run_cell_sync(cell, kwargs)
+
+ async def set_ui_element_value(
+ self, request: SetUIElementValueRequest
+ ) -> bool:
+ return await self._app._set_ui_element_value(request)
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.py
index 5af995b47f..841c46b0cc 100644
--- a/marimo/_plugins/ui/_core/registry.py
+++ b/marimo/_plugins/ui/_core/registry.py
@@ -12,7 +12,7 @@ if sys.version_info < (3, 10):
else:
from typing import TypeAlias
-from marimo._ast.app import App, _Namespace
+from marimo._ast.app import _Namespace
from marimo._ast.cell import CellId_t
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import get_context
@@ -93,16 +93,6 @@ class UIElementRegistry:
value, _Namespace
) and self._find_bindings_in_namespace(object_id, value):
bindings.add(name)
- elif (
- isinstance(value, App)
- and value._cached_defs is not None
- and self._find_bindings_in_namespace(
- object_id, value._cached_defs
- )
- ):
- # app composition -- only one level of nesting is currently
- # supported
- bindings.add(name)
return bindings
def _register_bindings(self, object_id: UIElementId) -> None:
diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.py
index b51a2d6389..12c809ae07 100644
--- a/marimo/_plugins/ui/_core/ui_element.py
+++ b/marimo/_plugins/ui/_core/ui_element.py
@@ -28,6 +28,7 @@ from marimo._runtime.functions import Function
if TYPE_CHECKING:
from marimo._plugins.ui._impl.input import form as form_plugin
+ from marimo._runtime.context.types import RuntimeContext
# S: Type of frontend value
# - the initial value sent to the frontend must be of type S
@@ -137,19 +138,6 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
self._initialize(*self._args)
self._initialized = True
- try:
- ctx = get_context()
- except ContextNotInitializedError:
- pass
- else:
- # When the UI element is destructed, it should be removed
- # from the UIElementRegistry (which only holds a weakref to it).
- finalizer = weakref.finalize(
- self, ctx.ui_element_registry.delete, self._id, id(self)
- )
- # No need to clean up the registry at program teardown
- finalizer.atexit = False
-
def _initialize(
self,
component_name: str,
@@ -194,13 +182,26 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
except (ids.NoIDProviderException, ContextNotInitializedError):
self._id = self._random_id
+ self._ctx: RuntimeContext | None
try:
- ctx = get_context()
+ # cache the context in case the UI element is constructed
+ # in a nested context -- so that if the UI element is accessed
+ # in the root context (eg with app_result.defs["elem"].value),
+ # the correct constructing context is retrieved
+ self._ctx = get_context()
except ContextNotInitializedError:
- ctx = None
+ self._ctx = None
+ else:
+ # When the UI element is destructed, it should be removed
+ # from the UIElementRegistry (which only holds a weakref to it).
+ finalizer = weakref.finalize(
+ self, self._ctx.ui_element_registry.delete, self._id, id(self)
+ )
+ # No need to clean up the registry at program teardown
+ finalizer.atexit = False
- if ctx is not None:
- ctx.ui_element_registry.register(self._id, self)
+ if self._ctx is not None:
+ self._ctx.ui_element_registry.register(self._id, self)
# an Instantiate request may want us to override the initial value
try:
# NB: If a cell produces a non-deterministic set of
@@ -213,13 +214,15 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
# TODO(akshayka): parametrize UIElement with an optional
# string ID, so users can provide their own IDs to make
# sure a mismatch never happens ...
- initial_value = cast(S, ctx.get_ui_initial_value(self._id))
+ initial_value = cast(
+ S, self._ctx.get_ui_initial_value(self._id)
+ )
except KeyError:
# we weren't asked to override the UI element's value
pass
for function in functions:
- ctx.function_registry.register(
+ self._ctx.function_registry.register(
namespace=self._id, function=function
)
self._initial_value_frontend = initial_value
@@ -259,17 +262,15 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
@property
def value(self) -> T:
"""The element's current value."""
- try:
- ctx = get_context()
- except ContextNotInitializedError:
+ if self._ctx is None:
return self._value
if (
- ctx.execution_context is not None
- and not ctx.execution_context.setting_element_value
+ self._ctx.execution_context is not None
+ and not self._ctx.execution_context.setting_element_value
and (
- ctx.execution_context.cell_id
- == ctx.ui_element_registry.get_cell(self._id)
+ self._ctx.execution_context.cell_id
+ == self._ctx.ui_element_registry.get_cell(self._id)
)
):
raise RuntimeError(
@@ -436,6 +437,14 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):
Composite UIElement may need to override this method to run
their own side-effects.
"""
- duplicate = copy.deepcopy(self)
- duplicate._initialize(*self._args)
+ # context is not deepcopy-able because it has a thread lock;
+ # temporarily unset it during the clone.
+ ctx = self._ctx
+ try:
+ self._ctx = None
+ duplicate = copy.deepcopy(self)
+ duplicate._ctx = ctx
+ duplicate._initialize(*self._args)
+ finally:
+ self._ctx = ctx
return duplicate
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index bb1a3243f8..a6023ed4c1 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -335,8 +335,10 @@ def launch_pyodide_kernel(
stdout=stdout,
stderr=stderr,
stdin=stdin,
+ module=patches.patch_main_module(
+ file=app_metadata.filename, input_override=input_override
+ ),
enqueue_control_request=lambda req: control_queue.put_nowait(req),
- input_override=input_override,
debugger_override=debugger,
user_config=user_config,
)
diff --git a/marimo/_runtime/app/common.py b/marimo/_runtime/app/common.py
new file mode 100644
index 0000000000..9378ebdc41
--- /dev/null
+++ b/marimo/_runtime/app/common.py
@@ -0,0 +1,11 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, Dict, Tuple
+
+from marimo._ast.cell import CellId_t
+
+OutputsType = Dict[CellId_t, Any]
+DefsType = Dict[str, Any]
+
+RunOutput = Tuple[OutputsType, DefsType]
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
new file mode 100644
index 0000000000..6f97551653
--- /dev/null
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -0,0 +1,117 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import weakref
+from typing import TYPE_CHECKING, Any
+
+from marimo._ast.cell import CellId_t, CellImpl
+from marimo._config.config import DEFAULT_CONFIG
+from marimo._runtime.app.common import RunOutput
+from marimo._runtime.context.types import get_context
+from marimo._runtime.patches import create_main_module
+from marimo._runtime.requests import (
+ AppMetadata,
+ ExecutionRequest,
+ SetUIElementValueRequest,
+)
+from marimo._runtime.runner import cell_runner
+
+if TYPE_CHECKING:
+ from marimo._ast.app import InternalApp
+
+
+class AppKernelRunner:
+ """Runs an app in a kernel context; used for composition."""
+
+ def __init__(self, app: InternalApp) -> None:
+ from marimo._runtime.context.kernel_context import (
+ KernelRuntimeContext,
+ create_kernel_context,
+ )
+ from marimo._runtime.runner.hooks_post_execution import (
+ _reset_matplotlib_context,
+ )
+ from marimo._runtime.runtime import Kernel
+
+ self.app = app
+ self._outputs: dict[str, Any] = {}
+
+ ctx = get_context()
+ if not isinstance(ctx, KernelRuntimeContext):
+ raise RuntimeError("AppKernelRunner requires a kernel context.")
+
+ def cache_output(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+ ) -> None:
+ """Update the app's cached outputs."""
+ from marimo._plugins.stateless.flex import vstack
+
+ del runner
+ if (
+ run_result.output is None
+ and run_result.accumulated_output is not None
+ ):
+ self.outputs[cell.cell_id] = vstack(
+ run_result.accumulated_output
+ )
+ else:
+ self.outputs[cell.cell_id] = run_result.output
+
+ filename = "<unknown>"
+ self._kernel = Kernel(
+ cell_configs={},
+ app_metadata=AppMetadata({}, {}, filename),
+ stream=ctx.stream,
+ stdout=None,
+ stderr=None,
+ stdin=None,
+ module=create_main_module(filename, None),
+ user_config=DEFAULT_CONFIG,
+ enqueue_control_request=lambda _: None,
+ post_execution_hooks=[cache_output, _reset_matplotlib_context],
+ )
+
+ # We push a new runtime context onto the "stack", corresponding to this
+ # app. The context is removed when the app object is destroyed.
+ self._runtime_context = create_kernel_context(
+ kernel=self._kernel,
+ app=app,
+ stream=ctx.stream,
+ stdout=None,
+ stderr=None,
+ virtual_files_supported=True,
+ parent=ctx,
+ )
+ ctx.add_child(self._runtime_context)
+ finalizer = weakref.finalize(
+ self, ctx.remove_child, self._runtime_context
+ )
+ finalizer.atexit = False
+
+ @property
+ def outputs(self) -> dict[CellId_t, Any]:
+ return self._outputs
+
+ @property
+ def globals(self) -> dict[CellId_t, Any]:
+ return self._kernel.globals
+
+ async def run(self, cells_to_run: set[CellId_t]) -> RunOutput:
+ execution_requests = [
+ ExecutionRequest(cell_id=cid, code=cell._cell.code)
+ for cid in cells_to_run
+ if (cell := self.app.cell_manager.cell_data_at(cid).cell)
+ is not None
+ ]
+
+ with self._runtime_context.install():
+ await self._kernel.run(execution_requests)
+ return self.outputs, self._kernel.globals
+
+ async def set_ui_element_value(
+ self, request: SetUIElementValueRequest
+ ) -> bool:
+ with self._runtime_context.install():
+ return await self._kernel.set_ui_element_value(request)
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
new file mode 100644
index 0000000000..84bf53c10e
--- /dev/null
+++ b/marimo/_runtime/app/script_runner.py
@@ -0,0 +1,134 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+from typing import TYPE_CHECKING, Any, Callable, Iterator
+
+from marimo._ast.cell import CellId_t, CellImpl
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.types import NoopStream
+from marimo._runtime.app.common import RunOutput
+from marimo._runtime.context.types import (
+ get_context,
+ runtime_context_installed,
+ teardown_context,
+)
+from marimo._runtime.executor import execute_cell, execute_cell_async
+from marimo._runtime.patches import (
+ create_main_module,
+ patch_main_module_context,
+)
+
+if TYPE_CHECKING:
+ from marimo._ast.app import InternalApp
+
+
+class AppScriptRunner:
+ """Runs an app in a script context."""
+
+ def __init__(self, app: InternalApp) -> None:
+ self.app = app
+
+ def run(self) -> RunOutput:
+ from marimo._runtime.context.script_context import (
+ initialize_script_context,
+ )
+
+ app = self.app
+
+ is_async = False
+ for cell in app.cell_manager.cells():
+ if cell is None:
+ raise RuntimeError(
+ "Unparsable cell encountered. This is a bug in marimo, "
+ "please raise an issue."
+ )
+
+ if cell._is_coroutine():
+ is_async = True
+ break
+
+ installed_script_context = False
+ try:
+ if not runtime_context_installed():
+ # script context is ephemeral, only installed while the app is
+ # running
+ initialize_script_context(app=app, stream=NoopStream())
+ installed_script_context = True
+
+ # 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()
+
+ post_execute_hooks = []
+ if DependencyManager.has_matplotlib():
+ from marimo._output.mpl import close_figures
+
+ post_execute_hooks.append(close_figures)
+
+ if is_async:
+ outputs, defs = asyncio.run(
+ self._run_asynchronous(
+ post_execute_hooks=post_execute_hooks,
+ )
+ )
+ else:
+ outputs, defs = self._run_synchronous(
+ post_execute_hooks=post_execute_hooks,
+ )
+ return outputs, defs
+ finally:
+ if installed_script_context:
+ teardown_context()
+
+ def _cell_iterator(self) -> Iterator[CellImpl]:
+ app = self.app
+ for cid in app.execution_order:
+ cell = app.cell_manager.cell_data_at(cid).cell
+ if cell is None:
+ continue
+
+ if cell is not None and not app.graph.is_disabled(cid):
+ yield cell._cell
+
+ def _run_synchronous(
+ self,
+ post_execute_hooks: list[Callable[[], Any]],
+ ) -> RunOutput:
+ with patch_main_module_context(
+ create_main_module(file=None, input_override=None)
+ ) as module:
+ glbls = module.__dict__
+ outputs: dict[CellId_t, Any] = {}
+ for cell in self._cell_iterator():
+ with get_context().with_cell_id(cell.cell_id):
+ output = execute_cell(cell, glbls, self.app.graph)
+ for hook in post_execute_hooks:
+ hook()
+ outputs[cell.cell_id] = output
+ return outputs, glbls
+
+ async def _run_asynchronous(
+ self,
+ post_execute_hooks: list[Callable[[], Any]],
+ ) -> RunOutput:
+ with patch_main_module_context(
+ create_main_module(file=None, input_override=None)
+ ) as module:
+ glbls = module.__dict__
+ outputs: dict[CellId_t, Any] = {}
+ for cell in self._cell_iterator():
+ with get_context().with_cell_id(cell.cell_id):
+ output = await execute_cell_async(
+ cell, glbls, self.app.graph
+ )
+ for hook in post_execute_hooks:
+ hook()
+ outputs[cell.cell_id] = output
+ return outputs, glbls
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index e287b66c06..6275138bca 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -18,6 +18,7 @@ from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.params import CLIArgs, QueryParams
if TYPE_CHECKING:
+ from marimo._ast.app import InternalApp
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
from marimo._runtime.runtime import Kernel
@@ -29,6 +30,8 @@ class KernelRuntimeContext(RuntimeContext):
"""Encapsulates runtime state for a session."""
_kernel: Kernel
+ # app that owns this context; None for top-level contexts
+ _app: Optional[InternalApp] = None
_id_provider: Optional[IDProvider] = None
@property
@@ -99,23 +102,27 @@ class KernelRuntimeContext(RuntimeContext):
finally:
self._kernel.execution_context = old
+ @property
+ def app(self) -> InternalApp:
+ assert self._app is not None
+ return self._app
-def initialize_kernel_context(
+
+def create_kernel_context(
kernel: Kernel,
stream: Stream,
stdout: Stdout | None,
stderr: Stderr | None,
virtual_files_supported: bool = True,
-) -> None:
- """Initializes thread-local/session-specific context.
-
- Must be called exactly once for each client thread.
- """
+ app: InternalApp | None = None,
+ parent: KernelRuntimeContext | None = None,
+) -> KernelRuntimeContext:
from marimo._plugins.ui._core.registry import UIElementRegistry
from marimo._runtime.virtual_file import VirtualFileRegistry
- runtime_context = KernelRuntimeContext(
+ return KernelRuntimeContext(
_kernel=kernel,
+ _app=app,
ui_element_registry=UIElementRegistry(),
function_registry=FunctionRegistry(),
cell_lifecycle_registry=CellLifecycleRegistry(),
@@ -124,5 +131,24 @@ def initialize_kernel_context(
stream=stream,
stdout=stdout,
stderr=stderr,
+ children=[],
+ parent=parent,
+ )
+
+
+def initialize_kernel_context(
+ kernel: Kernel,
+ stream: Stream,
+ stdout: Stdout | None,
+ stderr: Stderr | None,
+ virtual_files_supported: bool = True,
+) -> None:
+ """Initializes thread-local/session-specific context.
+
+ Must be called exactly once for each client thread.
+ """
+ initialize_context(
+ runtime_context=create_kernel_context(
+ kernel, stream, stdout, stderr, virtual_files_supported
+ )
)
- initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index ce7eee1040..eb80ccd3d7 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -5,7 +5,6 @@ from contextlib import contextmanager
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Iterator, Optional
-from marimo._ast.app import InternalApp
from marimo._cli.parse_args import args_from_argv
from marimo._plugins.ui._core.ids import NoIDProviderException
from marimo._plugins.ui._core.registry import UIElementRegistry
@@ -20,6 +19,7 @@ from marimo._runtime.functions import FunctionRegistry
from marimo._runtime.params import CLIArgs, QueryParams
if TYPE_CHECKING:
+ from marimo._ast.app import InternalApp
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
from marimo._runtime.state import State
@@ -100,6 +100,10 @@ class ScriptRuntimeContext(RuntimeContext):
finally:
self._app.set_execution_context(old)
+ @property
+ def app(self) -> InternalApp:
+ return self._app
+
def initialize_script_context(app: InternalApp, stream: Stream) -> None:
"""Initializes thread-local/session-specific context.
@@ -118,5 +122,7 @@ def initialize_script_context(app: InternalApp, stream: Stream) -> None:
stream=stream,
stdout=None,
stderr=None,
+ children=[],
+ parent=None,
)
initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index 44fefa91a0..c5c632a9c7 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -18,6 +18,7 @@ from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistry
from marimo._runtime.functions import FunctionRegistry
if TYPE_CHECKING:
+ from marimo._ast.app import InternalApp
from marimo._ast.cell import CellId_t
from marimo._messaging.types import Stream
from marimo._output.hypertext import Html
@@ -66,6 +67,8 @@ class RuntimeContext(abc.ABC):
stream: Stream
stdout: Stdout | None
stderr: Stderr | None
+ children: list[RuntimeContext]
+ parent: RuntimeContext | None
@property
@abc.abstractmethod
@@ -122,6 +125,29 @@ class RuntimeContext(abc.ABC):
def with_cell_id(self, cell_id: CellId_t) -> Iterator[None]:
pass
+ def add_child(self, runtime_context: RuntimeContext) -> None:
+ if runtime_context not in self.children:
+ self.children.append(runtime_context)
+
+ def remove_child(self, runtime_context: RuntimeContext) -> None:
+ self.children.remove(runtime_context)
+ assert runtime_context not in self.children
+
+ @contextmanager
+ def install(self) -> Iterator[None]:
+ global _THREAD_LOCAL_CONTEXT
+ old_ctx = _THREAD_LOCAL_CONTEXT.runtime_context
+ try:
+ _THREAD_LOCAL_CONTEXT.runtime_context = self
+ yield
+ finally:
+ _THREAD_LOCAL_CONTEXT.runtime_context = old_ctx
+
+ @property
+ @abc.abstractmethod
+ def app(self) -> InternalApp:
+ pass
+
class _ThreadLocalContext(threading.local):
"""Thread-local container that holds thread/session-specific state."""
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index 554a018e68..7454ade8ca 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -116,15 +116,9 @@ del Loader; del MetaPathFinder
)
-def patch_main_module(
+def create_main_module(
file: str | None, input_override: Callable[[Any], str] | None
) -> types.ModuleType:
- """Patches __main__ module
-
- - Makes functions pickleable
- - Loads some overrides and mocks into globals
- """
-
# Every kernel gets its own main module, whose __dict__ attribute
# serves as the global namespace
_module = types.ModuleType(
@@ -143,6 +137,19 @@ def patch_main_module(
"__file__", sys.modules["__main__"].__file__
)
+ return _module
+
+
+def patch_main_module(
+ file: str | None, input_override: Callable[[Any], str] | None
+) -> types.ModuleType:
+ """Patches __main__ module
+
+ - Makes functions pickleable
+ - Loads some overrides and mocks into globals
+ """
+ _module = create_main_module(file, input_override)
+
# TODO(akshayka): In run mode, this can introduce races between different
# kernel threads, since they each share sys.modules. Unfortunately, Python
# doesn't provide a way for different threads to have their own sys.modules
@@ -160,10 +167,11 @@ def patch_main_module(
@contextlib.contextmanager
def patch_main_module_context(
- file: str | None = None, input_override: Callable[[Any], str] | None = None
+ module: types.ModuleType,
) -> Iterator[types.ModuleType]:
main = sys.modules["__main__"]
try:
- yield patch_main_module(file, input_override)
+ sys.modules["__main__"] = module
+ yield module
finally:
sys.modules["__main__"] = main
diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.py
index d58aff9e91..93053bca33 100644
--- a/marimo/_runtime/redirect_streams.py
+++ b/marimo/_runtime/redirect_streams.py
@@ -52,12 +52,22 @@ def redirect_streams(
stderr: Stderr | None,
stdin: Stdin | None,
) -> Iterator[None]:
+ cell_id_old = stream.cell_id
+
+ # In a nested context; NOOP so messages still reach the top-level cell.
+ if cell_id_old is not None:
+ try:
+ yield
+ finally:
+ ...
+ return
+
stream.cell_id = cell_id
if stdout is None or stderr is None:
try:
yield
finally:
- stream.cell_id = None
+ stream.cell_id = cell_id_old
return
# NB: Python doesn't allow monkey patching methods builtins, so
@@ -78,4 +88,4 @@ def redirect_streams(
sys.stdout = py_stdout
sys.stderr = py_stderr
sys.stdin = py_stdin
- stream.cell_id = None
+ stream.cell_id = cell_id_old
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index f6b9db1ac9..cf90e97e19 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -11,19 +11,13 @@ import traceback
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Union
-from marimo._ast.cell import (
- CellId_t,
- CellImpl,
-)
+from marimo._ast.cell import CellId_t, CellImpl
from marimo._config.config import ExecutionType, OnCellChangeType
from marimo._loggers import marimo_logger
from marimo._messaging.errors import Error, MarimoStrictExecutionError
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime import dataflow
-from marimo._runtime.control_flow import (
- MarimoInterrupt,
- MarimoStopError,
-)
+from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.executor import (
MarimoMissingRefError,
execute_cell,
@@ -37,6 +31,12 @@ if TYPE_CHECKING:
from collections.abc import Sequence
from marimo._runtime.context.types import ExecutionContext
+ from marimo._runtime.runner.hooks_on_finish import OnFinishHookType
+ from marimo._runtime.runner.hooks_post_execution import (
+ PostExecutionHookType,
+ )
+ from marimo._runtime.runner.hooks_pre_execution import PreExecutionHookType
+ from marimo._runtime.runner.hooks_preparation import PreparationHookType
from marimo._runtime.state import State
@@ -78,14 +78,10 @@ class Runner:
[CellId_t], contextlib._GeneratorContextManager[ExecutionContext]
]
| None = None,
- preparation_hooks: Sequence[Callable[["Runner"], Any]] | None = None,
- pre_execution_hooks: Sequence[Callable[[CellImpl, "Runner"], Any]]
- | None = None,
- post_execution_hooks: Sequence[
- Callable[[CellImpl, "Runner", RunResult], Any]
- ]
- | None = None,
- on_finish_hooks: Sequence[Callable[["Runner"], Any]] | None = None,
+ preparation_hooks: Sequence[PreparationHookType] | None = None,
+ pre_execution_hooks: Sequence[PreExecutionHookType] | None = None,
+ post_execution_hooks: Sequence[PostExecutionHookType] | None = None,
+ on_finish_hooks: Sequence[OnFinishHookType] | None = None,
):
self.graph = graph
self.debugger = debugger
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
index dfb524fc42..a3abc68d69 100644
--- a/marimo/_runtime/runner/hooks_on_finish.py
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -1,4 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Callable
+
from marimo import _loggers
from marimo._messaging.errors import (
Error,
@@ -14,6 +18,8 @@ from marimo._runtime.runner import cell_runner
LOGGER = _loggers.marimo_logger()
+OnFinishHookType = Callable[[cell_runner.Runner], None]
+
def _send_interrupt_errors(runner: cell_runner.Runner) -> None:
if runner.cells_to_run:
@@ -81,4 +87,7 @@ def _send_cancellation_errors(runner: cell_runner.Runner) -> None:
)
-ON_FINISH_HOOKS = [_send_interrupt_errors, _send_cancellation_errors]
+ON_FINISH_HOOKS: list[OnFinishHookType] = [
+ _send_interrupt_errors,
+ _send_cancellation_errors,
+]
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 5effa5b3e9..20c861bd0e 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -1,6 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from typing import Callable
+
from marimo import _loggers
from marimo._ast.cell import CellImpl
from marimo._data.get_datasets import get_datasets_from_variables
@@ -26,6 +28,10 @@ from marimo._utils.flatten import flatten
LOGGER = _loggers.marimo_logger()
+PostExecutionHookType = Callable[
+ [CellImpl, cell_runner.Runner, cell_runner.RunResult], None
+]
+
def _set_status_idle(
cell: CellImpl,
@@ -189,7 +195,7 @@ def _reset_matplotlib_context(
exec("__marimo__._output.mpl.close_figures()", runner.glbls)
-POST_EXECUTION_HOOKS = [
+POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [
_set_status_idle,
_store_reference_to_output,
_broadcast_variables,
diff --git a/marimo/_runtime/runner/hooks_pre_execution.py b/marimo/_runtime/runner/hooks_pre_execution.py
index f7c42348ff..8aed36df82 100644
--- a/marimo/_runtime/runner/hooks_pre_execution.py
+++ b/marimo/_runtime/runner/hooks_pre_execution.py
@@ -1,7 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Callable
+
from marimo._ast.cell import CellImpl
from marimo._runtime.runner import cell_runner
+PreExecutionHookType = Callable[[CellImpl, cell_runner.Runner], None]
+
def _set_staleness(
cell: CellImpl,
@@ -27,4 +33,7 @@ def _set_status_to_running(
cell.set_status("running")
-PRE_EXECUTION_HOOKS = [_set_staleness, _set_status_to_running]
+PRE_EXECUTION_HOOKS: list[PreExecutionHookType] = [
+ _set_staleness,
+ _set_status_to_running,
+]
diff --git a/marimo/_runtime/runner/hooks_preparation.py b/marimo/_runtime/runner/hooks_preparation.py
index b34e80d0fa..ab32eb3a73 100644
--- a/marimo/_runtime/runner/hooks_preparation.py
+++ b/marimo/_runtime/runner/hooks_preparation.py
@@ -1,7 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Callable
+
from marimo._runtime import dataflow
from marimo._runtime.runner import cell_runner
+PreparationHookType = Callable[[cell_runner.Runner], None]
+
def _update_stale_statuses(runner: cell_runner.Runner) -> None:
graph = runner.graph
@@ -22,4 +28,4 @@ def _update_stale_statuses(runner: cell_runner.Runner) -> None:
graph.cells[cid].set_stale(stale=False)
-PREPARATION_HOOKS = [_update_stale_statuses]
+PREPARATION_HOOKS: list[PreparationHookType] = [_update_stale_statuses]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 45772d744c..d08446016f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -19,7 +19,6 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, cast
from uuid import uuid4
from marimo import _loggers
-from marimo._ast.app import App
from marimo._ast.cell import CellConfig, CellId_t
from marimo._ast.compiler import compile_cell
from marimo._ast.visitor import Name
@@ -107,6 +106,10 @@ from marimo._runtime.runner.hooks import (
PRE_EXECUTION_HOOKS,
PREPARATION_HOOKS,
)
+from marimo._runtime.runner.hooks_on_finish import OnFinishHookType
+from marimo._runtime.runner.hooks_post_execution import PostExecutionHookType
+from marimo._runtime.runner.hooks_pre_execution import PreExecutionHookType
+from marimo._runtime.runner.hooks_preparation import PreparationHookType
from marimo._runtime.state import State
from marimo._runtime.utils.set_ui_element_request_manager import (
SetUIElementRequestManager,
@@ -121,6 +124,7 @@ from marimo._utils.variables import is_local
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
+ from types import ModuleType
from marimo._plugins.ui._core.ui_element import UIElement
@@ -268,9 +272,9 @@ class Kernel:
- stdout: replacement for sys.stdout
- stderr: replacement for sys.stderr
- stdin: replacement for sys.stdin
- - input_override: a function that overrides the builtin input() function
- - debugger_override: a replacement for the built-in Pdb
+ - module: module in which to execute code
- enqueue_control_request: callback to enqueue control requests
+ - debugger_override: a replacement for the built-in Pdb
"""
def __init__(
@@ -282,8 +286,12 @@ class Kernel:
stdout: Stdout | None,
stderr: Stderr | None,
stdin: Stdin | None,
+ module: ModuleType,
enqueue_control_request: Callable[[ControlRequest], None],
- input_override: Callable[[Any], str] = input_override,
+ preparation_hooks: list[PreparationHookType] | None = None,
+ pre_execution_hooks: list[PreExecutionHookType] | None = None,
+ post_execution_hooks: list[PostExecutionHookType] | None = None,
+ on_finish_hooks: list[OnFinishHookType] | None = None,
debugger_override: marimo_pdb.MarimoPdb | None = None,
) -> None:
self.app_metadata = app_metadata
@@ -294,6 +302,26 @@ class Kernel:
self.stderr = stderr
self.stdin = stdin
self.enqueue_control_request = enqueue_control_request
+
+ self._preparation_hooks = (
+ preparation_hooks
+ if preparation_hooks is not None
+ else PREPARATION_HOOKS
+ )
+ self._pre_execution_hooks = (
+ pre_execution_hooks
+ if pre_execution_hooks is not None
+ else PRE_EXECUTION_HOOKS
+ )
+ self._post_execution_hooks = (
+ post_execution_hooks
+ if post_execution_hooks is not None
+ else POST_EXECUTION_HOOKS
+ )
+ self._on_finish_hooks = (
+ on_finish_hooks if on_finish_hooks is not None else ON_FINISH_HOOKS
+ )
+
self._globals_lock = threading.RLock()
self._completion_worker_started = False
@@ -301,9 +329,7 @@ class Kernel:
if self.debugger is not None:
patches.patch_pdb(self.debugger)
- self._module = patches.patch_main_module(
- file=self.app_metadata.filename, input_override=input_override
- )
+ self._module = module
if self.app_metadata.filename is not None:
# TODO(akshayka): When a file is renamed / moved to another folder,
# we need to update sys.path.
@@ -888,13 +914,13 @@ class Kernel:
# sys.modules. Races can still happen, but this should help in most
# common cases. We could also be more aggressive and run this before
# every cell, or even before pickle.dump/pickle.dumps()
- patches.patch_sys_module(self._module)
- while cell_ids := await self._run_cells_internal(cell_ids):
- LOGGER.debug("Running state updates ...")
- if self.lazy() and cell_ids:
- self.graph.set_stale(cell_ids)
- break
- LOGGER.debug("Finished run.")
+ with patches.patch_main_module_context(self._module):
+ while cell_ids := await self._run_cells_internal(cell_ids):
+ LOGGER.debug("Running state updates ...")
+ if self.lazy() and cell_ids:
+ self.graph.set_stale(cell_ids)
+ break
+ LOGGER.debug("Finished run.")
async def _run_cells_internal(self, roots: set[CellId_t]) -> set[CellId_t]:
"""Run cells, send outputs to frontends
@@ -953,11 +979,13 @@ class Kernel:
execution_mode=self.reactive_execution_mode,
execution_type=self.execution_type,
execution_context=self._install_execution_context,
- preparation_hooks=PREPARATION_HOOKS + [invalidate_state],
- pre_execution_hooks=PRE_EXECUTION_HOOKS,
- post_execution_hooks=POST_EXECUTION_HOOKS,
- on_finish_hooks=ON_FINISH_HOOKS
- + [broadcast_missing_packages, propagate_kernel_errors],
+ preparation_hooks=self._preparation_hooks + [invalidate_state],
+ pre_execution_hooks=self._pre_execution_hooks,
+ post_execution_hooks=self._post_execution_hooks,
+ on_finish_hooks=(
+ self._on_finish_hooks
+ + [broadcast_missing_packages, propagate_kernel_errors]
+ ),
)
# I/O
@@ -1052,10 +1080,12 @@ class Kernel:
async def set_ui_element_value(
self, request: SetUIElementValueRequest
- ) -> None:
+ ) -> bool:
"""Set the value of a UI element bound to a global variable.
Runs cells that reference the UI element by name.
+
+ Returns True if any ui elements were set, False otherwise
"""
updated_components: list[UIElement[Any, Any]] = []
@@ -1063,14 +1093,37 @@ class Kernel:
# of another parent element is resolved to its parent. In particular,
# interacting with a view triggers reactive execution through the
# source (parent).
+ ctx = get_context()
resolved_requests: dict[str, Any] = {}
- ui_element_registry = get_context().ui_element_registry
+ referring_cells: set[CellId_t] = set()
+ ui_element_registry = ctx.ui_element_registry
for object_id, value in request.ids_and_values:
try:
resolved_id, resolved_value = ui_element_registry.resolve_lens(
object_id, value
)
except (KeyError, RuntimeError):
+ # Attempt to set the UI element in a child context (app).
+ for child_context in ctx.children:
+ if (
+ child_context.app is not None
+ and await child_context.app.set_ui_element_value(
+ SetUIElementValueRequest(
+ object_ids=[object_id], values=[value]
+ )
+ )
+ ):
+ bindings = [
+ name
+ for name, value in self.globals.items()
+ # child_context.app is an InternalApp object
+ if value is child_context.app._app
+ ]
+ for binding in bindings:
+ referring_cells.update(
+ self.graph.get_referring_cells(binding)
+ )
+
# KeyError: Trying to access an unnamed UIElement
# RuntimeError: UIElement was deleted somehow
LOGGER.debug(
@@ -1080,7 +1133,6 @@ class Kernel:
resolved_requests[resolved_id] = resolved_value
del request
- referring_cells: set[CellId_t] = set()
for object_id, value in resolved_requests.items():
try:
component = ui_element_registry.get_object(object_id)
@@ -1131,9 +1183,7 @@ class Kernel:
bound_names = (
name
- for name in get_context().ui_element_registry.bound_names(
- object_id
- )
+ for name in ctx.ui_element_registry.bound_names(object_id)
if not is_local(name)
)
@@ -1143,12 +1193,6 @@ class Kernel:
variable_values.append(
VariableValue(name=name, value=component)
)
- if name in self.globals and isinstance(
- self.globals[name], App
- ):
- self.globals[name]._register_ui_element_update(
- value=component
- )
try:
# subtracting self.graph.definitions[name]: never rerun the
# cell that created the name
@@ -1199,6 +1243,8 @@ class Kernel:
tmpio.seek(0)
write_traceback(tmpio.read())
+ return bool(updated_components) or bool(referring_cells)
+
def get_ui_initial_value(self, object_id: str) -> Any:
"""Get an initial value for a UIElement, if any
@@ -1499,7 +1545,9 @@ def launch_kernel(
stdout=stdout,
stderr=stderr,
stdin=stdin,
- input_override=input_override,
+ module=patches.patch_main_module(
+ file=app_metadata.filename, input_override=input_override
+ ),
debugger_override=debugger,
user_config=user_config,
enqueue_control_request=lambda req: control_queue.put_nowait(req),
diff --git a/marimo/_smoke_tests/appcomp/double_nested/inner.py b/marimo/_smoke_tests/appcomp/double_nested/inner.py
new file mode 100644
index 0000000000..ebb9efc009
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/double_nested/inner.py
@@ -0,0 +1,52 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mo.md("# Innermost")
+ return
+
+
+def __(mo):
+ x = mo.ui.number(1, 10)
+ return x,
+
+
+def __(x):
+ x
+ return
+
+
+def __(mo):
+ y = mo.ui.number(1, 10)
+ return y,
+
+
+def __(y):
+ y
+ return
+
+
+def __(x, y):
+ x.value + y.value
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/double_nested/main.py b/marimo/_smoke_tests/appcomp/double_nested/main.py
new file mode 100644
index 0000000000..accc41a714
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/double_nested/main.py
@@ -0,0 +1,29 @@
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ from middle import app as middle
+ return middle,
+
+
+async def __(middle):
+ result = await middle.embed()
+ result.output
+ return result,
+
+
+def __(result):
+ result.defs["x_plus_y"]
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/double_nested/middle.py b/marimo/_smoke_tests/appcomp/double_nested/middle.py
new file mode 100644
index 0000000000..ba58969ef1
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/double_nested/middle.py
@@ -0,0 +1,41 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __():
+ from inner import app
+ return app,
+
+
+def __(mo):
+ mo.md("# middle")
+ return
+
+
+def __(mo, result):
+ x_plus_y = result.defs['x'].value + result.defs['y'].value
+ mo.md(f"The middle app has calculated `x_plus_y` ... try retrieving it")
+ return x_plus_y,
+
+
+async def __(app):
+ result = await app.embed()
+ result.output
+ return result,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/imperative_output/imperative_output.py b/marimo/_smoke_tests/appcomp/imperative_output/imperative_output.py
new file mode 100644
index 0000000000..82f2608ee8
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/imperative_output/imperative_output.py
@@ -0,0 +1,38 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ mo.md("# hello")
+ return
+
+
+def __(mo, time):
+ for i in mo.status.progress_bar(range(5)):
+ time.sleep(0.5)
+ print(i)
+ return i,
+
+
+def __(mo):
+ import time
+ mo.output.replace(mo.md("# output"))
+ time.sleep(0.5)
+ mo.output.replace(mo.md("# replaced"))
+ return time,
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/imperative_output/main.py b/marimo/_smoke_tests/appcomp/imperative_output/main.py
new file mode 100644
index 0000000000..c640d2b056
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/imperative_output/main.py
@@ -0,0 +1,27 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ from imperative_output import app
+ return app,
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+async def __(app):
+ (await app.embed()).output
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/inner.py b/marimo/_smoke_tests/appcomp/inner.py
index a2fa74a651..ebb9efc009 100644
--- a/marimo/_smoke_tests/appcomp/inner.py
+++ b/marimo/_smoke_tests/appcomp/inner.py
@@ -1,21 +1,27 @@
# Copyright 2024 Marimo. All rights reserved.
+
import marimo
-__generated_with = "0.6.22"
+__generated_with = "0.6.26"
app = marimo.App()
@app.cell
def __():
import marimo as mo
+ return mo,
+
- return (mo,)
+def __(mo):
+ mo.md("# Innermost")
+ return
@app.cell
def __(mo):
x = mo.ui.number(1, 10)
- return (x,)
+ return x,
@app.cell
@@ -27,7 +33,7 @@ def __(x):
@app.cell
def __(mo):
y = mo.ui.number(1, 10)
- return (y,)
+ return y,
@app.cell
diff --git a/marimo/_smoke_tests/appcomp/outer.py b/marimo/_smoke_tests/appcomp/main.py
similarity index 51%
rename from marimo/_smoke_tests/appcomp/outer.py
rename to marimo/_smoke_tests/appcomp/main.py
index 6f33a6405b..a2d453a8a0 100644
--- a/marimo/_smoke_tests/appcomp/outer.py
+++ b/marimo/_smoke_tests/appcomp/main.py
@@ -2,8 +2,8 @@
import marimo
-__generated_with = "0.6.22"
-app = marimo.App()
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
@app.cell
@@ -19,26 +19,34 @@ def __(mo):
@app.cell
-def __(app):
- app
+async def __(app):
+ result = await app.embed()
+ result.output
+ return result,
+
+
+def __(result):
+ result.defs["x"].value
return
@app.cell
-def __(app):
- app
+def __(result):
+ result.defs["y"].value
return
[email protected](hide_code=True)
def __(mo):
mo.md("## Render an app inside tabs")
return
@app.cell
-def __(app, mo):
- tabs = mo.ui.tabs({"🧮": app, "📝": mo.md("Hello world")}); tabs
+async def __(app, mo):
+ tabs = mo.ui.tabs({"🧮": (await app.embed()).output, "📝": mo.md("Hello world")})
+ tabs
return tabs,
@@ -55,8 +63,20 @@ def __():
@app.cell
-def __(table_app):
- table_app
+async def __(table_app):
+ table_app_results = await table_app.embed()
+ return table_app_results,
+
+
+def __(table_app_results):
+ table_app_results.output
+ return
+
+
+def __(table_app_results):
+ table_app_results.defs
return
diff --git a/marimo/_smoke_tests/appcomp/state/main.py b/marimo/_smoke_tests/appcomp/state/main.py
new file mode 100644
index 0000000000..9ef9918599
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/state/main.py
@@ -0,0 +1,21 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ from state import app
+ return app,
+
+
+async def __(app):
+ (await app.embed()).output
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/appcomp/state/state.py b/marimo/_smoke_tests/appcomp/state/state.py
new file mode 100644
index 0000000000..15aa61c561
--- /dev/null
+++ b/marimo/_smoke_tests/appcomp/state/state.py
@@ -0,0 +1,34 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.26"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return mo,
+
+
+def __(mo):
+ get_state, set_state = mo.state(False)
+ return get_state, set_state
+
+
+def __(mo, set_state):
+ b = mo.ui.button(on_change=lambda x: set_state(True))
+ b
+ return b,
+
+
+def __(get_state):
+ "button was clicked" if get_state() else "button was not clicked"
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 19d8ac966c..f4d183a953 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -7,7 +7,7 @@ import textwrap
from typing import TYPE_CHECKING, Any
import pytest
-from marimo._ast.app import App, _AppConfig
+from marimo._ast.app import App, _AppConfig, InternalApp
from marimo._ast.errors import (
CycleError,
DeleteNonlocalError,
@@ -513,21 +513,24 @@ def test_cli_args(tmp_path: pathlib.Path) -> None:
class TestAppComposition:
- def test_app_as_html(self) -> None:
+ async def test_app_embed(self) -> None:
app = App()
@app.cell
def __() -> None:
+ x = 1
"hello"
@app.cell
def __() -> None:
"world"
- app_html = as_html(app).text
- assert app_html == vstack(["hello", "world"]).text
+ result = await app.embed()
+ assert result.output.text == vstack(["hello", "world"]).text
+ assert set(result.defs.keys()) == set(["x"])
+ assert result.defs["x"] == 1
- def test_app_as_html_none_stripped(self) -> None:
+ async def test_app_embed_none_stripped(self) -> None:
app = App()
@app.cell
@@ -542,21 +545,10 @@ class TestAppComposition:
def __() -> None:
"world"
- app_html = as_html(app).text
+ result = await app.embed()
# None shouldn't show up in output
- assert app_html == vstack(["hello", "world"]).text
-
- def test_app_as_html_is_cached(self) -> None:
- app = App()
-
- @app.cell
- def __() -> None:
- import random
-
- random.randint(0, 10000)
-
- # the app should only run once
- assert as_html(app).text == as_html(app).text
+ assert result.output.text == vstack(["hello", "world"]).text
+ assert not result.defs
async def test_app_comp_basic(
self, k: Kernel, exec_req: ExecReqProvider
@@ -573,7 +565,7 @@ class TestAppComposition:
import random
token = random.randint(0, 10000)
- app
+ result = await app.embed()
"""
),
]
@@ -583,12 +575,12 @@ class TestAppComposition:
# store the token value now, so we can make sure it changes later,
# ie can make sure cell re-ran
token = k.globals["token"]
- app = k.globals["app"]
+ result = k.globals["result"]
# dropdown has name d in app
- dropdown_element = app._cached_defs["d"]
+ dropdown_element = result.defs["d"]
assert dropdown_element.value == "first"
- html = as_html(app).text
+ html = result.output.text
assert "value is first" in html
assert "value is second" not in html
@@ -598,13 +590,12 @@ class TestAppComposition:
)
)
assert token != k.globals["token"]
- assert not app._pending_ui_element_updates
# make sure ui element value updated
assert dropdown_element.value == "second"
# make sure cell referencing app re-ran
-
- html = as_html(app).text
+ result = k.globals["result"]
+ html = result.output.text
assert "value is first" not in html
assert "value is second" in html
@@ -620,17 +611,17 @@ class TestAppComposition:
),
exec_req.get(
"""
- app
+ result = await app.embed()
"""
),
]
)
assert not k.errors
- app = k.globals["app"]
+ result = k.globals["result"]
# two number inputs: x and y
- x = app._cached_defs["x"]
- y = app._cached_defs["y"]
+ x = result.defs["x"]
+ y = result.defs["y"]
assert x.value == 1
assert y.value == 1
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 868858ffd5..bc6c0b21b8 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -20,6 +20,7 @@ from marimo._messaging.types import NoopStream
from marimo._plugins.ui._core.ids import IDProvider
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.dataflow import EdgeWithVar
+from marimo._runtime.patches import create_main_module
from marimo._runtime.requests import (
AppMetadata,
CreationRequest,
@@ -34,7 +35,6 @@ from tests.conftest import ExecReqProvider, MockedKernel
if TYPE_CHECKING:
import pathlib
- from types import ModuleType
def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:
@@ -179,9 +179,11 @@ class TestExecution:
array
"""
await k.run([exec_req.get(code=cell_one_code)])
+ assert not k.errors
# Reference the array's value
await k.run([er := exec_req.get(code="x = array.value[0] + 1")])
+ assert not k.errors
assert k.globals["x"] == 2
# Set a child of the array to 5 ...
@@ -743,12 +745,8 @@ class TestExecution:
assert k.globals["pickle_output"] is not None
def test_sys_path_updated(self, tmp_path: pathlib.Path) -> None:
- main: ModuleType | None = None
try:
filename = str(tmp_path / "notebook.py")
- if "__main__" in sys.modules:
- # kernel patches __main__; need to reset it after test
- main = sys.modules["__main__"]
Kernel(
stream=NoopStream(),
stdout=None,
@@ -760,14 +758,13 @@ class TestExecution:
query_params={}, filename=filename, cli_args={}
),
enqueue_control_request=lambda _: None,
+ module=create_main_module(None, None),
)
assert str(tmp_path) in sys.path
assert str(tmp_path) == sys.path[0]
finally:
if str(tmp_path) in sys.path:
sys.path.remove(str(tmp_path))
- if main is not None:
- sys.modules["__main__"] = main
async def test_set_config_before_registering_cell(
self, any_kernel: Kernel, exec_req: ExecReqProvider
diff --git a/tests/conftest.py b/tests/conftest.py
index 9be49f7f34..86599807db 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -21,8 +21,10 @@ from marimo._messaging.streams import (
ThreadSafeStream,
)
from marimo._output.formatters.formatters import register_formatters
+from marimo._runtime import patches
from marimo._runtime.context import teardown_context
from marimo._runtime.context.kernel_context import initialize_kernel_context
+from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import AppMetadata, ExecutionRequest
from marimo._runtime.runtime import Kernel
@@ -93,6 +95,9 @@ class MockedKernel:
self.stderr = MockStderr(self.stream)
self.stdin = MockStdin(self.stream)
self._main = sys.modules["__main__"]
+ module = patches.patch_main_module(
+ file=None, input_override=input_override
+ )
self.k = Kernel(
stream=self.stream,
@@ -106,6 +111,7 @@ class MockedKernel:
),
debugger_override=MarimoPdb(stdout=self.stdout, stdin=self.stdin),
enqueue_control_request=lambda _: None,
+ module=module,
)
initialize_kernel_context(