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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: app comp (#1665)
Akshay Agrawal31eea4bdcffc
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex afb324c4f0..b08e3f1a89 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -14,6 +14,7 @@ from typing import (Mapping,Optional,)+from uuid import uuid4from marimo import _loggersfrom marimo._ast.cell import (@@ -33,7 +34,9 @@ from marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.types import NoopStreamfrom marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime import dataflow+from marimo._runtime.context.types import get_contextfrom marimo._runtime.executor import (execute_cell,execute_cell_async,@@ -103,8 +106,11 @@ class CellData:class _Namespace(Mapping[str, object]):- def __init__(self, dictionary: dict[str, object]) -> None:+ def __init__(+ self, dictionary: dict[str, object], owner: Cell | App+ ) -> None:self._dict = dictionary+ self._owner = ownerdef __getitem__(self, item: str) -> object:return self._dict[item]@@ -145,6 +151,11 @@ class App:self._unparsable = Falseself._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+def cell(self,func: Callable[..., Any] | None = None,@@ -236,32 +247,46 @@ class App:finally:self._initialized = True+ 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)+ )+def _outputs_and_defs(self, outputs: dict[CellId_t, Any], glbls: dict[str, Any]- ) -> tuple[Sequence[Any], dict[str, Any]]:- # Return+ ) -> tuple[Sequence[Any], _Namespace]:+ # Returns# - the outputs, sorted in the order that cells were added to the# graph# - dict of defs -> values- return (- tuple(- outputs[cid]- for cid in self._cell_manager.valid_cell_ids()- if not self._graph.is_disabled(cid)- ),- # omit defs that were never defined at runtime, eg due to- # conditional definitions like- #- # if cond:- # x = 0- {name: glbls[name] for name in self._defs if name in glbls},++ # 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(+ dictionary={+ name: glbls[name] for name in self._defs if name in glbls+ },+ owner=self,)- def _run_sync(- self, post_execute_hooks: list[Callable[..., Any]]- ) -> tuple[Sequence[Any], dict[str, Any]]:- from marimo._runtime.context.types import ExecutionContext+ 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 scriptwith patch_main_module_context() as module:@@ -270,20 +295,38 @@ class App: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):- self._execution_context = ExecutionContext(- cell_id=cid, setting_element_value=False- )- outputs[cid] = execute_cell(cell._cell, glbls, self._graph)- for hook in post_execute_hooks:- hook()- return self._outputs_and_defs(outputs, glbls)+ 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(- self, post_execute_hooks: list[Callable[..., Any]]- ) -> tuple[Sequence[Any], dict[str, Any]]:- from marimo._runtime.context.types import ExecutionContext-+ 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 scriptwith patch_main_module_context() as module:@@ -292,20 +335,39 @@ class App:outputs: dict[CellId_t, Any] = {}for cid in self._execution_order:cell = self._cell_manager.cell_data_at(cid).cell- if cell is not None and not self._graph.is_disabled(cid):- self._execution_context = ExecutionContext(- cell_id=cid, setting_element_value=False- )- outputs[cid] = await execute_cell_async(- cell._cell, glbls, self._graph- )- for hook in post_execute_hooks:- hook()- self._execution_context = None-- return self._outputs_and_defs(outputs, glbls)+ 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- def run(self) -> tuple[Sequence[Any], dict[str, Any]]:+ 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,)@@ -356,16 +418,31 @@ class App:post_execute_hooks.append(close_figures)- if is_async:- return asyncio.run(- self._run_async(post_execute_hooks=post_execute_hooks)- )- else:- return self._run_sync(post_execute_hooks=post_execute_hooks)+ # 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()+async def _run_cell_async(self, cell: Cell, kwargs: dict[str, Any]) -> tuple[Any, _Namespace]:@@ -373,14 +450,52 @@ class App:output, defs = await self._runner.run_cell_async(cell._cell.cell_id, kwargs)- return output, _Namespace(defs)+ return output, _Namespace(defs, owner=self)def _run_cell_sync(self, cell: Cell, kwargs: dict[str, Any]) -> tuple[Any, _Namespace]:self._maybe_initialize()output, defs = self._runner.run_cell_sync(cell._cell.cell_id, kwargs)- return output, _Namespace(defs)+ 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)++ def _mime_(self) -> tuple[KnownMimeType, str]:+ from marimo._plugins.stateless.flex import vstack++ 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,+ )+ 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:@@ -564,6 +679,11 @@ class InternalApp:def execution_context(self) -> ExecutionContext | None:return self._app._execution_context+ def set_execution_context(+ self, execution_context: ExecutionContext | None+ ) -> None:+ self._app._execution_context = execution_context+@propertydef runner(self) -> dataflow.Runner:self._app._maybe_initialize()diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex 841c46b0cc..5af995b47f 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 _Namespace+from marimo._ast.app import App, _Namespacefrom marimo._ast.cell import CellId_tfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import get_context@@ -93,6 +93,16 @@ 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 bindingsdef _register_bindings(self, object_id: UIElementId) -> None:diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.pyindex 6b84e1bd0a..e287b66c06 100644--- a/marimo/_runtime/context/kernel_context.py+++ b/marimo/_runtime/context/kernel_context.py@@ -84,6 +84,21 @@ class KernelRuntimeContext(RuntimeContext):def register_state_update(self, state: State[Any]) -> None:return self._kernel.register_state_update(state)+ @contextmanager+ def with_cell_id(self, cell_id: CellId_t) -> Iterator[None]:+ old = self.execution_context+ try:+ if old is not None:+ setting_element_value = old.setting_element_value+ else:+ setting_element_value = False+ self._kernel.execution_context = ExecutionContext(+ cell_id=cell_id, setting_element_value=setting_element_value+ )+ yield+ finally:+ self._kernel.execution_context = old+def initialize_kernel_context(kernel: Kernel,diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.pyindex 1bb95fa52a..ce7eee1040 100644--- a/marimo/_runtime/context/script_context.py+++ b/marimo/_runtime/context/script_context.py@@ -82,6 +82,24 @@ class ScriptRuntimeContext(RuntimeContext):del statereturn+ @contextmanager+ def with_cell_id(self, cell_id: CellId_t) -> Iterator[None]:+ old = self.execution_context+ try:+ if old is not None:+ setting_element_value = old.setting_element_value+ else:+ setting_element_value = False+ self._app.set_execution_context(+ ExecutionContext(+ cell_id=cell_id,+ setting_element_value=setting_element_value,+ )+ )+ yield+ finally:+ self._app.set_execution_context(old)+def initialize_script_context(app: InternalApp, stream: Stream) -> None:"""Initializes thread-local/session-specific context.diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.pyindex 8d6fcab2c0..44fefa91a0 100644--- a/marimo/_runtime/context/types.py+++ b/marimo/_runtime/context/types.py@@ -117,6 +117,11 @@ class RuntimeContext(abc.ABC):def register_state_update(self, state: State[Any]) -> None:pass+ @contextmanager+ @abc.abstractmethod+ def with_cell_id(self, cell_id: CellId_t) -> Iterator[None]:+ pass+class _ThreadLocalContext(threading.local):"""Thread-local container that holds thread/session-specific state."""diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 21875fa476..2c9fd08cca 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, castfrom uuid import uuid4from marimo import _loggers+from marimo._ast.app import Appfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._ast.compiler import compile_cellfrom marimo._ast.visitor import Name@@ -1125,12 +1126,19 @@ class Kernel:variable_values: list[VariableValue] = []for name in bound_names:- # subtracting self.graph.definitions[name]: never rerun the- # cell that created the name+ # TODO update variable values even for namespaces? lenses? etcvariable_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 namereferring_cells.update(self.graph.get_referring_cells(name)- self.graph.get_defining_cells(name)@@ -1237,6 +1245,9 @@ class Kernel:# elements associated with its owning cell. But that# means we won't be able to restore their values# on reconnection.+ #+ # TODO(akshayka): Do UI elements created in function calls+ # get cleared from the FE registry? This could be a leak.try:response = function(request.args)if asyncio.iscoroutine(response):diff --git a/marimo/_smoke_tests/appcomp/inner.py b/marimo/_smoke_tests/appcomp/inner.pynew file mode 100644index 0000000000..a2fa74a651--- /dev/null+++ b/marimo/_smoke_tests/appcomp/inner.py@@ -0,0 +1,46 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.6.22"+app = marimo.App()+++def __():+ import marimo as mo++ return (mo,)+++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/make_table.py b/marimo/_smoke_tests/appcomp/make_table.pynew file mode 100644index 0000000000..f580a08523--- /dev/null+++ b/marimo/_smoke_tests/appcomp/make_table.py@@ -0,0 +1,27 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.6.22"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ t = mo.ui.table({"a": [1, 2, 3], "b": [4, 5, 6]})+ return t,+++def __(t):+ t+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/appcomp/outer.py b/marimo/_smoke_tests/appcomp/outer.pynew file mode 100644index 0000000000..6f33a6405b--- /dev/null+++ b/marimo/_smoke_tests/appcomp/outer.py@@ -0,0 +1,70 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.6.22"+app = marimo.App()+++def __():+ from inner import app+ return app,++[email protected](hide_code=True)+def __(mo):+ mo.md("## Render the same app multiple times")+ return+++def __(app):+ app+ return+++def __(app):+ app+ return++[email protected](hide_code=True)+def __(mo):+ mo.md("## Render an app inside tabs")+ return+++def __(app, mo):+ tabs = mo.ui.tabs({"🧮": app, "📝": mo.md("Hello world")}); tabs+ return tabs,+++def __(mo):+ mo.md(rf"## Render an app that uses function calls")+ return+++def __():+ from make_table import app as table_app+ return table_app,+++def __(table_app):+ table_app+ return+++def __():+ import marimo as mo+ return mo,+++if __name__ == "__main__":+ app.run()diff --git a/pyproject.toml b/pyproject.tomlindex 18f32f6ef7..8c9769f62e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -159,10 +159,12 @@ exclude = ["marimo/_test_utils/codegen_data","marimo/_test_utils/_tutorials","marimo/_static/files/wasm-intro.py",+ "tests/_ast/app_data","tests/_ast/codegen_data","tests/_ast/cell_data","tests/_cli/ipynb_data","tests/_runtime/runtime_data",+ "tests/_ast/test_app.py","frontend","docs","build",@@ -262,6 +264,7 @@ fixture-parentheses = falsestrict = trueexclude = ['examples',+ 'tests/_ast/app_data','tests/_ast/codegen_data','tests/_ast/cell_data','tests/_cli/ipynb_data',@@ -280,7 +283,7 @@ ignore_errors = true[tool.pytest.ini_options]minversion = "6.0"-addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_data"+addopts = "-ra -q -v --ignore tests/_cli/ipynb_data --ignore tests/_ast/codegen_data --ignore tests/_ast/app_data"testpaths = ["tests",]diff --git a/tests/_ast/app_data/calculator.py b/tests/_ast/app_data/calculator.pynew file mode 100644index 0000000000..a2fa74a651--- /dev/null+++ b/tests/_ast/app_data/calculator.py@@ -0,0 +1,46 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.6.22"+app = marimo.App()+++def __():+ import marimo as mo++ return (mo,)+++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/tests/_ast/app_data/ui_element_dropdown.py b/tests/_ast/app_data/ui_element_dropdown.pynew file mode 100644index 0000000000..eec434e6e0--- /dev/null+++ b/tests/_ast/app_data/ui_element_dropdown.py@@ -0,0 +1,32 @@+import marimo++__generated_with = "0.6.22"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ d = mo.ui.dropdown(["first", "second"], value="first")+ return d,+++def __(d):+ d+ return+++def __(d):+ "value is " + d.value+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.pyindex 30d982057c..c58b8bd7b2 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -1,4 +1,5 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotationsimport subprocess@@ -6,7 +7,6 @@ import textwrapfrom typing import TYPE_CHECKING, Anyimport pytest-from marimo._ast.app import App, _AppConfigfrom marimo._ast.errors import (CycleError,@@ -15,6 +15,11 @@ from marimo._ast.errors import (UnparsableError,)from marimo._dependencies.dependencies import DependencyManager+from marimo._output.formatting import as_html+from marimo._plugins.stateless.flex import vstack+from marimo._runtime.requests import SetUIElementValueRequest+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProviderif TYPE_CHECKING:import pathlib@@ -352,7 +357,8 @@ class TestApp:@app.celldef __() -> tuple[Any]:- def foo() -> None: ...+ def foo() -> None:+ ...return (foo,)@@ -485,3 +491,141 @@ def test_cli_args(tmp_path: pathlib.Path) -> None:assert "value1" in outputassert "bar" in outputassert "value2" in output+++class TestAppComposition:+ def test_app_as_html(self) -> None:+ app = App()++ @app.cell+ def __() -> None:+ "hello"++ @app.cell+ def __() -> None:+ "world"++ app_html = as_html(app).text+ assert app_html == vstack(["hello", "world"]).text++ def test_app_as_html_none_stripped(self) -> None:+ app = App()++ @app.cell+ def __() -> None:+ "hello"++ @app.cell+ def __() -> None:+ None++ @app.cell+ def __() -> None:+ "world"++ app_html = as_html(app).text+ # 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++ async def test_app_comp_basic(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from app_data.ui_element_dropdown import app+ """+ ),+ exec_req.get(+ """+ import random++ token = random.randint(0, 10000)+ app+ """+ ),+ ]+ )+ assert not k.errors++ # 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"]+ # dropdown has name d in app+ dropdown_element = app._cached_defs["d"]+ assert dropdown_element.value == "first"++ html = as_html(app).text+ assert "value is first" in html+ assert "value is second" not in html++ await k.set_ui_element_value(+ SetUIElementValueRequest.from_ids_and_values(+ [(dropdown_element._id, ["second"])]+ )+ )+ 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+ assert "value is first" not in html+ assert "value is second" in html++ async def test_app_comp_multiple_ui_elements(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from app_data.calculator import app+ """+ ),+ exec_req.get(+ """+ app+ """+ ),+ ]+ )+ assert not k.errors++ app = k.globals["app"]+ # two number inputs: x and y+ x = app._cached_defs["x"]+ y = app._cached_defs["y"]+ assert x.value == 1+ assert y.value == 1++ # testing that only descendants of the updated UI elements run,+ # and that the other UI element is not reset+ await k.set_ui_element_value(+ SetUIElementValueRequest.from_ids_and_values([(x._id, 2)])+ )+ assert x.value == 2+ assert y.value == 1++ await k.set_ui_element_value(+ SetUIElementValueRequest.from_ids_and_values([(y._id, 3)])+ )++ assert x.value == 2+ assert y.value == 3