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: add reactive execution on `ui.array` and `ui.dictionary`'s contained elements (#690)
Akshay Agrawald7a062ab6589
diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex 56ae2a456b..ad5f13c8e9 100644--- a/marimo/_plugins/ui/_core/registry.py+++ b/marimo/_plugins/ui/_core/registry.py@@ -1,16 +1,25 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import sysimport weakref-from typing import Any, Iterable+from typing import Any, Dict, Iterable, TypeVar, Union++if sys.version_info < (3, 10):+ from typing_extensions import TypeAlias+else:+ from typing import TypeAlias-from marimo import _loggersfrom marimo._ast.cell import CellId_tfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import get_contextUIElementId = str-LOGGER = _loggers.marimo_logger()++T = TypeVar("T")++# Recursive types don't support | or dict[] in py3.8/3.9+LensValue: TypeAlias = Union[T, Dict[str, "LensValue[T]"]]class UIElementRegistry:@@ -36,6 +45,8 @@ class UIElementRegistry:self._objects[object_id] = weakref.ref(ui_element)assert kernel.execution_context is not Noneself._constructing_cells[object_id] = kernel.execution_context.cell_id+ # bindings must be lazily registered, since there aren't any+ # bindings at UIElement object creation timeif object_id in self._bindings:# If `register` is called on an object_id that is being# reused before `delete` is called, bindings won't have been@@ -62,18 +73,67 @@ class UIElementRegistry:)self._bindings[object_id] = names+ def get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:+ if object_id not in self._objects:+ raise KeyError(f"UIElement with id {object_id} not found")+ # UI elements are only updated if a global is bound to it. This ensures+ # that the UI element update triggers reactivity, but also means that+ # elements stored as, say, attributes on an object won't be updated.+ if not self.bound_names(object_id):+ raise NameError(f"UIElement with id {object_id} has no bindings")+ obj = self._objects[object_id]()+ assert obj is not None+ return obj++ def get_cell(self, object_id: UIElementId) -> CellId_t:+ return self._constructing_cells[object_id]++ def resolve_lens(+ self, object_id: UIElementId, value: LensValue[T]+ ) -> tuple[str, LensValue[T]]:+ """Resolve a lens, if any, to an object id and value update++ Returns (resolved object id, resolved value)++ Raises KeyError if `object_id` does not exist in the registry,+ RuntimeError if the object was deleted.+ """+ if object_id not in self._objects:+ raise KeyError(f"UIElement with id {object_id} not found")+ obj = self._objects[object_id]()+ if obj is None:+ raise RuntimeError(f"UIElement with id {object_id} was deleted")++ lens = obj._lens+ if lens is None:+ # Base case: the element has no lens, so the resolved+ # update is the same as what was passed in.+ return (object_id, value)++ resolved_value = {lens.key: value}+ return self.resolve_lens(lens.parent_id, resolved_value)+def delete(self, object_id: UIElementId, python_id: int) -> None:+ """Delete a UI element from the registry++ This function may be called by the Python garbage collector, while+ a cell is executing. For this reason we make sure not to log+ anything -- these logs would show up as console output in the+ frontend, confusing the user.+ """if object_id not in self._objects:returnui_element = self._objects[object_id]()- registered_python_id = id(ui_element)- if registered_python_id != python_id:+ registered_python_id = (+ id(ui_element) if ui_element is not None else None+ )+ if (+ registered_python_id is not None+ and registered_python_id != python_id+ ):# guards against UIElement's destructor racing against# registration of another element when a cell re-runs- LOGGER.debug(- "Python id mismatch when deleting UI element %s", object_id- )returnif ui_element is not None:@@ -83,18 +143,3 @@ class UIElementRegistry:del self._bindings[object_id]if object_id in self._constructing_cells:del self._constructing_cells[object_id]-- def get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:- if object_id not in self._objects:- raise KeyError(f"UIElement with id {object_id} not found")- # UI elements are only updated if a global is bound to it. This ensures- # that the UI element update triggers reactivity, but also means that- # elements stored as, say, attributes on an object won't be updated.- if not self.bound_names(object_id):- raise NameError(f"UIElement with id {object_id} has no bindings")- obj = self._objects[object_id]()- assert obj is not None- return obj-- def get_cell(self, object_id: UIElementId) -> CellId_t:- return self._constructing_cells[object_id]diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex fe1a1c2482..21c884b5a8 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport abcimport copyimport uuid+from dataclasses import dataclassfrom typing import (TYPE_CHECKING,Any,@@ -41,6 +42,23 @@ T = TypeVar("T")LOGGER = _loggers.marimo_logger()+@dataclass+class Lens:+ """Track how a view of a higher-order element relates to its source++ Higher-order UI elements support lensing, ie extracting their children+ as "views". These views can be embedded in other outputs and interacted+ with.++ UI elements that are views of a higher-order element (eg, an entry of+ an array is a view of the array) have a lens object that stores the+ id of its parent UI element, and the key at which its parent stores it.+ """++ parent_id: str+ key: str++class MarimoConvertValueException(Exception):pass@@ -125,6 +143,12 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):Split out from __init__ so _clone() typechecks"""+ # A UIElement may be a child ("lens") of another UI element.+ #+ # Set with self._register_as_view() after initialization, since parents+ # are usually created after the child is created+ self._lens: Lens | None = None+# Random token## Every element is annotated with a random token, which by design is@@ -225,6 +249,10 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):"""pass+ def _register_as_view(self, parent: UIElement[Any, Any], key: str) -> None:+ """Register this element as a view of `parent`."""+ self._lens = Lens(parent_id=parent._id, key=key)+@propertydef value(self) -> T:"""The element's current value."""diff --git a/marimo/_plugins/ui/_impl/array.py b/marimo/_plugins/ui/_impl/array.pyindex e74e8e4878..b4bce055b0 100644--- a/marimo/_plugins/ui/_impl/array.py+++ b/marimo/_plugins/ui/_impl/array.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Dict, Final, Optional, Sequence+from typing import Any, Callable, Dict, Final, Iterator, Optional, Sequencefrom marimo._output.formatters.structures import format_structurefrom marimo._output.rich_help import mddoc@@ -19,14 +19,19 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):Use an array to- - create a set of UI elements at runtime+ - create a dynamic number of UI elements at runtime- group together logically related UI elements- keep the number of global variables in your program small- Access the values of the elements using the `value` attribute of the- array.+ Access the values of the elements using the `value` attribute of the array+ (`array.value`).- The UI elements in the array are clones of the original elements:+ The elements in the array can be accessed using square brackets+ (`array[index]`) and embedded in other marimo outputs. You can also+ iterate over the UI elements using the `in` operator (`for element in+ array`).++ Note: The UI elements in the array are clones of the original elements:interacting with the array will _not_ update the original elements, andvice versa.@@ -46,6 +51,12 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):array.value```+ Access and output a UI element in the array:++ ```python+ mo.md(f"This is a slider: array[0]")+ ```+Some number of UI elements, determined at runtime:```python@@ -95,6 +106,9 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):on_change=on_change,)+ for i, element in enumerate(self._elements):+ element._register_as_view(self, key=str(i))+@propertydef elements(self) -> Sequence[UIElement[JSONType, object]]:return self._elements@@ -110,3 +124,18 @@ class array(UIElement[Dict[str, JSONType], Sequence[object]]):def _clone(self) -> array:return array(elements=self.elements, label=self._label)++ def __len__(self) -> int:+ return len(self.elements)++ def __getitem__(self, key: int) -> UIElement[JSONType, object]:+ return self.elements[key]++ def __iter__(self) -> Iterator[UIElement[JSONType, object]]:+ return self.elements.__iter__()++ def __reversed__(self) -> Iterator[UIElement[JSONType, object]]:+ return self.elements.__reversed__()++ def __contains__(self, item: UIElement[JSONType, object]) -> bool:+ return item in self.elementsdiff --git a/marimo/_plugins/ui/_impl/batch.py b/marimo/_plugins/ui/_impl/batch.pyindex f787b8d4a2..3f2adc6487 100644--- a/marimo/_plugins/ui/_impl/batch.py+++ b/marimo/_plugins/ui/_impl/batch.py@@ -1,7 +1,14 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Callable, Dict, Final, Optional+import sys++if sys.version_info < (3, 9):+ from typing import ItemsView, ValuesView+else:+ from collections.abc import ItemsView, ValuesView++from typing import Any, Callable, Dict, Final, Iterator, Optionalfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc@@ -42,10 +49,37 @@ class _batch_base(UIElement[Dict[str, JSONType], Dict[str, object]]):on_change=on_change,)+ for key, element in self._elements.items():+ element._register_as_view(parent=self, key=key)+@propertydef elements(self) -> dict[str, UIElement[JSONType, object]]:return self._elements+ def __len__(self) -> int:+ return len(self.elements)++ def __getitem__(self, key: str) -> UIElement[JSONType, object]:+ return self.elements[key]++ def __iter__(self) -> Iterator[str]:+ return self.elements.__iter__()++ def __reversed__(self) -> Iterator[str]:+ return self.elements.__reversed__()++ def __contains__(self, item: str) -> bool:+ return item in self.elements++ def get(self, key: str, default: Any | None = None) -> Any:+ return self.elements.get(key, default)++ def items(self) -> ItemsView[str, UIElement[JSONType, object]]:+ return self.elements.items()++ def values(self) -> ValuesView[UIElement[JSONType, object]]:+ return self.elements.values()+def _convert_value(self, value: dict[str, JSONType]) -> dict[str, object]:if self._initialized:for k, v in value.items():diff --git a/marimo/_plugins/ui/_impl/dictionary.py b/marimo/_plugins/ui/_impl/dictionary.pyindex 9183796ff7..54e163b64a 100644--- a/marimo/_plugins/ui/_impl/dictionary.py+++ b/marimo/_plugins/ui/_impl/dictionary.py@@ -24,8 +24,12 @@ class dictionary(_batch_base):Access the values of the elements using the `value` attribute of thedictionary.- The UI elements in the dictionary are clones of the original elements:- interacting with the dictionary will _not_ update the original+ The elements in the dictionary can be accessed using square brackets+ (`dictionary[key]`) and embedded in other marimo outputs. You can also+ iterate over the UI elements using the same syntax used for Python dicts.++ Note: The UI elements in the dictionary are clones of the original+ elements: interacting with the dictionary will _not_ update the originalelements, and vice versa.**Examples.**@@ -48,6 +52,12 @@ class dictionary(_batch_base):d.value```+ Access and output a UI element in the array:++ ```python+ mo.md(f"This is a slider: d['slider']")+ ```+Some number of UI elements, determined at runtime:```python@@ -113,4 +123,6 @@ class dictionary(_batch_base):def _clone(self) -> dictionary:"""Custom clone method so new dict gets copies of UI elements."""- return dictionary(self.elements, label=self._label)+ return dictionary(+ self.elements, label=self._label, on_change=self._on_change+ )diff --git a/marimo/_runtime/redirect_streams.py b/marimo/_runtime/redirect_streams.pyindex 0cf7b298fc..95821f3abc 100644--- a/marimo/_runtime/redirect_streams.py+++ b/marimo/_runtime/redirect_streams.py@@ -72,8 +72,8 @@ def redirect_streams():yieldfinally:- # These have to be restored after the redirect context managers have- # exited+ # The redirect context manager relies on these being installed;+ # restore them after the context manager quitssys.stdout = py_stdoutsys.stderr = py_stderrsys.stdin = py_stdindiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 5f4c1833d6..fb3a0e28d2 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -855,12 +855,31 @@ class Kernel:Runs cells that reference the UI element by name."""- referring_cells = set()+ # Resolve lenses on request, if any: any element that is a view+ # of another parent element is resolved to its parent. In particular,+ # interacting with a view triggers reactive execution through the+ # source (parent).+ resolved_requests: dict[str, Any] = {}+ ui_element_registry = get_context().ui_element_registryfor object_id, value in request.ids_and_values:try:- component = get_context().ui_element_registry.get_object(- object_id+ resolved_id, resolved_value = ui_element_registry.resolve_lens(+ object_id, value+ )+ except (KeyError, RuntimeError):+ # KeyError: Trying to access an unnamed UIElement+ # RuntimeError: UIElement was deleted somehow+ LOGGER.debug(+ "Could not resolve UIElement with id%s", object_id)+ continue+ resolved_requests[resolved_id] = resolved_value+ del request++ referring_cells = set()+ for object_id, value in resolved_requests.items():+ try:+ component = ui_element_registry.get_object(object_id)LOGGER.debug("Setting value on UIElement with id %s, value %s",object_id,@@ -874,7 +893,7 @@ class Kernel:continuewith self._install_execution_context(- get_context().ui_element_registry.get_cell(object_id),+ ui_element_registry.get_cell(object_id),setting_element_value=True,):try:diff --git a/marimo/_smoke_tests/lens_test.py b/marimo/_smoke_tests/lens_test.pynew file mode 100644index 0000000000..fa4e9f0c8c--- /dev/null+++ b/marimo/_smoke_tests/lens_test.py@@ -0,0 +1,124 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.1.85"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __(mo):+ from functools import partial++ data = []+++ def append(v, i):+ del v+ data.append(i)+++ dict_template = {+ str(i): mo.ui.button(+ value=i,+ label=str(i),+ on_click=lambda v: v + 1,+ on_change=partial(append, i=i),+ )+ for i in range(3)+ }+++ x = mo.ui.dictionary(+ {+ str(i): mo.ui.button(+ value=i,+ label=str(i),+ on_click=lambda v: v + 1,+ on_change=partial(append, i=i),+ )+ for i in range(3)+ }+ )+ # x+ return append, data, dict_template, partial, x+++def __(mo, x):+ mo.ui.table([{"data": "foo", "button": btn} for btn in x.values()])+ return+++def __(data, x):+ # x.value counts how many times each button has been clicked+ # data is a log of button clicks+ x.value, data+ return+++def __(dict_template, mo):+ composite = mo.ui.array(+ [+ mo.ui.slider(1, 10),+ mo.ui.array([mo.ui.checkbox(False), mo.ui.slider(10, 20)]),+ mo.ui.dictionary(dict_template),+ ]+ )+ return composite,+++def __():+ 10+ return+++def __(composite):+ composite[0], composite[1], composite[2]+ return+++def __(composite, mo):+ mo.accordion({"Push a button": composite[2]["0"]})+ return+++def __(composite):+ composite.value+ return+++def __():+ def change_printer(v):+ print("changed ", v)+ return change_printer,+++def __(checkboxes):+ [_item for _item in checkboxes]+ return+++def __(change_printer, mo):+ checkboxes = mo.ui.array(+ [mo.ui.checkbox(False, on_change=change_printer) for i in range(5)]+ )+ return checkboxes,+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_core/test_registry.py b/tests/_plugins/ui/_core/test_registry.pynew file mode 100644index 0000000000..25bf3f9cf9--- /dev/null+++ b/tests/_plugins/ui/_core/test_registry.py@@ -0,0 +1,151 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo import ui+from marimo._runtime.context import get_context+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++def test_cached_element_still_registered(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ k.run(+ [+ exec_req.get("import functools"),+ exec_req.get("import marimo as mo"),+ exec_req.get(+ """+ @functools.lru_cache+ def slider():+ return mo.ui.slider(1, 10)+ """+ ),+ (construct_slider := exec_req.get("s = slider()")),+ ]+ )+ # Make sure that the slider is registered+ s = k.globals["s"]+ assert get_context().ui_element_registry.get_object(s._id) == s++ # Re-run the cell but fetch the same slider, since we're using+ # functools.cache. Make sure it's still registered!+ k.run([construct_slider])+ assert get_context().ui_element_registry.get_object(s._id) == s+++def test_resolve_simple_noop(executing_kernel: Kernel) -> None:+ del executing_kernel+ t = ui.text()+ registry = get_context().ui_element_registry+ assert registry.resolve_lens(t._id, "hello world") == (+ t._id,+ "hello world",+ )+++def test_resolve_array_noop(executing_kernel: Kernel) -> None:+ del executing_kernel+ array = ui.array([ui.text(), ui.slider(1, 10)])+ registry = get_context().ui_element_registry+ assert registry.resolve_lens(array._id, {"0": "hello world"}) == (+ array._id,+ {"0": "hello world"},+ )+++def test_resolve_lens_array(executing_kernel: Kernel) -> None:+ del executing_kernel+ array = ui.array([ui.text(), ui.slider(1, 10)])+ registry = get_context().ui_element_registry+ assert registry.resolve_lens(array[0]._id, "hello world") == (+ array._id,+ {"0": "hello world"},+ )+ assert registry.resolve_lens(array[1]._id, 5) == (+ array._id,+ {"1": 5},+ )+++def test_resolve_lens_nested(executing_kernel: Kernel) -> None:+ del executing_kernel++ # an array containing an array containing a dict+ dict_inner = ui.dictionary({"0": ui.text(), "1": ui.slider(1, 10)})+ array_inner = ui.array([ui.text(), ui.slider(1, 10), dict_inner])+ array = ui.array([ui.text(), ui.slider(1, 10), array_inner])++ registry = get_context().ui_element_registry++ # array resolves to itself+ assert registry.resolve_lens(array._id, {"0": "hello world"}) == (+ array._id,+ {"0": "hello world"},+ )++ # setting the simple elements of the array+ assert registry.resolve_lens(array[0]._id, "hello world") == (+ array._id,+ {"0": "hello world"},+ )+ assert registry.resolve_lens(array[1]._id, 5) == (+ array._id,+ {"1": 5},+ )++ # setting some elements of the inner array+ assert registry.resolve_lens(+ array[2]._id,+ {"0": "hello world", "1": 5},+ ) == (+ array._id,+ {"2": {"0": "hello world", "1": 5}},+ )+ assert registry.resolve_lens(+ array[2][0]._id,+ "hello world",+ ) == (+ array._id,+ {"2": {"0": "hello world"}},+ )+ assert registry.resolve_lens(+ array[2][1]._id,+ 5,+ ) == (+ array._id,+ {"2": {"1": 5}},+ )++ # setting some elements of the inner dict+ assert registry.resolve_lens(+ array[2][2]._id,+ {"0": "hello world", "1": 5},+ ) == (+ array._id,+ {"2": {"2": {"0": "hello world", "1": 5}}},+ )+ assert registry.resolve_lens(+ array[2][2]["1"]._id,+ 5,+ ) == (+ array._id,+ {"2": {"2": {"1": 5}}},+ )+++def test_lens_not_bound(k: Kernel, exec_req: ExecReqProvider) -> None:+ k.run(+ [+ exec_req.get(+ """+ import marimo as mo+ array = mo.ui.array([mo.ui.text(), mo.ui.slider(1, 10)])+ """+ )+ ]+ )+ array = k.globals["array"]+ registry = get_context().ui_element_registry+ assert not registry.bound_names(array[0]._id)+ assert registry.bound_names(array._id) == set(["array"])diff --git a/tests/_plugins/ui/_core/test_ui_element_registration.py b/tests/_plugins/ui/_core/test_ui_element_registration.pydeleted file mode 100644index a145383114..0000000000--- a/tests/_plugins/ui/_core/test_ui_element_registration.py+++ /dev/null@@ -1,35 +0,0 @@-# Copyright 2024 Marimo. All rights reserved.-from __future__ import annotations--from marimo._runtime.context import get_context-from marimo._runtime.runtime import Kernel-from tests.conftest import ExecReqProvider---# TODO: colocate test with UIElementRegistry file; requires refactoring-# pytest's conftests ...-def test_cached_element_still_registered(- k: Kernel, exec_req: ExecReqProvider-) -> None:- k.run(- [- exec_req.get("import functools"),- exec_req.get("import marimo as mo"),- exec_req.get(- """- @functools.lru_cache- def slider():- return mo.ui.slider(1, 10)- """- ),- (construct_slider := exec_req.get("s = slider()")),- ]- )- # Make sure that the slider is registered- s = k.globals["s"]- assert get_context().ui_element_registry.get_object(s._id) == s-- # Re-run the cell but fetch the same slider, since we're using- # functools.cache. Make sure it's still registered!- k.run([construct_slider])- assert get_context().ui_element_registry.get_object(s._id) == sdiff --git a/tests/_plugins/ui/_impl/test_array.py b/tests/_plugins/ui/_impl/test_array.pyindex 499fa46af1..178b8f3d2b 100644--- a/tests/_plugins/ui/_impl/test_array.py+++ b/tests/_plugins/ui/_impl/test_array.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import pytest+from marimo._plugins import ui@@ -72,3 +74,24 @@ def test_update_checks_against_frontend_value() -> None:# smoke test: don't check against backend value, which will raisearray._update({"0": ["option"]})assert len(array.value) == 1 and isinstance(array.value[0], NoEquality)+++def test_container_emulation() -> None:+ array = ui.array([ui.slider(1, 10), ui.text()])+ # len+ assert len(array) == 2+ # reversed+ assert list(reversed(array)) == list(reversed(array.elements))+ # getitem+ assert array[0] == array.elements[0]+ assert array[1] == array.elements[1]+ # iter+ for a, b in zip(array, array.elements):+ assert a == b+ # contains+ assert array[0] in array+ assert array[1] in array++ with pytest.raises(TypeError) as e:+ array[0] = 1+ assert "does not support item assignment" in str(e)diff --git a/tests/_plugins/ui/_impl/test_dictionary.py b/tests/_plugins/ui/_impl/test_dictionary.pyindex 45695991bd..a898883e56 100644--- a/tests/_plugins/ui/_impl/test_dictionary.py+++ b/tests/_plugins/ui/_impl/test_dictionary.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import pytest+from marimo._plugins import ui@@ -51,3 +53,35 @@ def test_update_on_frontend_value_change_only() -> None:d._update({"0": 2})d._update({"0": 2})assert d.value == {"0": 1}+++def test_container_emulation() -> None:+ d = ui.dictionary({"0": ui.slider(1, 10), "1": ui.text()})+ # len+ assert len(d) == 2+ # reversed+ assert list(reversed(d)) == list(reversed(d.elements))+ # getitem+ assert d["0"] == d.elements["0"]+ assert d["1"] == d.elements["1"]+ # iter+ for a, b in zip(d, d.elements):+ assert a == b+ # contains+ assert "0" in d+ assert "1" in d+ # get+ assert d.get("0") == d["0"]+ assert d.get("0", 123) == d["0"]+ assert d.get("2") is None+ # items+ assert list(d.items()) == list(d.elements.items())+ # value+ assert list(d.values()) == list(d.elements.values())++ with pytest.raises(TypeError) as e:+ d["0"] = 1+ assert "does not support item assignment" in str(e)++ with pytest.raises(KeyError) as e:+ d["2"]diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex c26b426e6e..ef0ff38fc5 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -84,6 +84,80 @@ def test_set_ui_element_value(k: Kernel) -> None:assert k.globals["x"] == 6+def test_set_ui_element_value_not_found_doesnt_fail(k: Kernel) -> None:+ # smoke test -- this shouldn't raise an exception+ k.set_ui_element_value(+ SetUIElementValueRequest([("does not exist", None)])+ )+++def test_set_ui_element_value_lensed(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ """Test setting the value of a lensed element.++ Make sure reactivity flows through its parent, and that its on_change+ handler is called exactly once.+ """+ k.run([exec_req.get(code="import marimo as mo")])++ # Create an array and output it ...+ cell_one_code = """+ data = []+ def on_change(v):+ data.append(v)++ array = mo.ui.array([mo.ui.slider(0, 10, value=1, on_change=on_change)]);+ array+ """+ k.run([exec_req.get(code=cell_one_code)])++ # Reference the array's value+ k.run([exec_req.get(code="x = array.value[0] + 1")])+ assert k.globals["x"] == 2++ # Set a child of the array to 5 ...+ child_id = k.globals["array"][0]._id+ k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))++ # Make sure the array and its child are updated+ assert k.globals["array"].value == [5]+ assert k.globals["array"][0].value == 5++ # Make sure the on_change handler got called exactly once+ assert k.globals["data"] == [5]++ # Make sure setting array's child triggered execution of the second cell,+ # which references `array`+ assert k.globals["x"] == 6+++def test_set_ui_element_value_lensed_with_state(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ """Test setting the value of a lensed element with on_change set_state"""+ k.run([exec_req.get(code="import marimo as mo")])++ # Create an array and output it ...+ cell_one_code = """+ get_state, set_state = mo.state(None)++ array = mo.ui.array(+ [mo.ui.slider(0, 10, value=1, on_change=set_state),+ mo.ui.slider(0, 10, value=1, on_change=set_state)+ ]);+ """+ k.run([exec_req.get(code=cell_one_code)])+ k.run([exec_req.get(code="state = get_state()")])++ # Set a child of the array and make sure its on_change handler is called+ child_id = k.globals["array"][0]._id+ k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))++ # Make sure the array and its child are updated+ assert k.globals["state"] == 5++def test_set_local_var_ui_element_value(k: Kernel) -> None:k.run([ExecutionRequest("0", "import marimo as mo")])k.run([ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")])diff --git a/tests/conftest.py b/tests/conftest.pyindex fa752c0bfb..38d9ec132e 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -111,6 +111,17 @@ def mocked_kernel() -> Generator[MockedKernel, None, None]:yield mocked+# Installs an execution context without stream redirection+def executing_kernel() -> Generator[Kernel, None, None]:+ mocked = MockedKernel()+ mocked.k.stdout = None+ mocked.k.stderr = None+ mocked.k.stdin = None+ with mocked.k._install_execution_context(cell_id="0"):+ yield mocked.k++# Factory to create ExecutionRequests and abstract away cell IDclass ExecReqProvider:def __init__(self) -> None: