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
fix: set-ui-element-value on local variable (#645)
Akshay Agrawal3c5c1db97092
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 44a5972417..b76099804b 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -18,7 +18,7 @@ from marimo._ast.cell import (CellId_t,cell_function,)-from marimo._ast.visitor import ScopedVisitor, _is_local+from marimo._ast.visitor import ScopedVisitor, is_localfrom marimo._utils.tmpdir import get_tmpdir@@ -85,7 +85,7 @@ def compile_cell(body = compile(module, body_filename, mode="exec")last_expr = compile(expr, last_expr_filename, mode="eval")- glbls = {name for name in v.defs if not _is_local(name)}+ glbls = {name for name in v.defs if not is_local(name)}return Cell(# keyed by original (user) code, for cache lookupskey=code_key(code),diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex 850c431c29..66a7dccdcd 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -10,7 +10,7 @@ from uuid import uuid4Name = str-def _is_local(name: str) -> bool:+def is_local(name: str) -> bool:return name.startswith("_") and not name.startswith("__")@@ -62,7 +62,7 @@ class ScopedVisitor(ast.NodeVisitor):self, name: str, ignore_scope: bool = False) -> str:"""Mangle local variable name declared at top-level scope."""- if _is_local(name) and (len(self.block_stack) == 1 or ignore_scope):+ if is_local(name) and (len(self.block_stack) == 1 or ignore_scope):return f"_{self.id}{name}"else:return name@@ -279,16 +279,16 @@ class ScopedVisitor(ast.NodeVisitor):elif (isinstance(node.ctx, ast.Load)and not self._is_defined(node.id)- and not _is_local(node.id)+ and not is_local(node.id)):self._add_ref(node.id, deleted=False)elif (isinstance(node.ctx, ast.Del)and not self._is_defined(node.id)- and not _is_local(node.id)+ and not is_local(node.id)):self._add_ref(node.id, deleted=True)- elif _is_local(node.id):+ elif is_local(node.id):mangled_name = self._if_local_then_mangle(node.id, ignore_scope=True)diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex c885c4a74f..3695b652e7 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -21,6 +21,7 @@ from typing import Any, Callable, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellConfig, CellId_tfrom marimo._ast.compiler import compile_cell+from marimo._ast.visitor import is_localfrom marimo._config.config import configurefrom marimo._messaging.errors import (Error,@@ -884,7 +885,7 @@ class Kernel:traceback.print_exc(file=tmpio)tmpio.seek(0)sys.stderr.write(tmpio.read())- # Don't run descendants+ # Don't run referring elements of this UI elementcontinueexcept Exception:# User's on_change handler an exception ...@@ -898,8 +899,12 @@ class Kernel:tmpio.seek(0)sys.stderr.write(tmpio.read())- bound_names = get_context().ui_element_registry.bound_names(- object_id+ bound_names = (+ name+ for name in get_context().ui_element_registry.bound_names(+ object_id+ )+ if not is_local(name))variable_values: list[VariableValue] = []@@ -909,10 +914,27 @@ class Kernel:variable_values.append(VariableValue(name=name, value=component))- referring_cells.update(- self.graph.get_referring_cells(name)- - self.graph.definitions[name]- )+ try:+ referring_cells.update(+ self.graph.get_referring_cells(name)+ - self.graph.definitions[name]+ )+ except Exception:+ # Internal marimo error+ sys.stderr.write(+ "An exception was raised when finding cells that "+ f"refer to a UIElement value, for bound name {name}. "+ "This is a bug in marimo. "+ "Please copy the below traceback and paste it in an "+ "issue: https://github.com/marimo-team/marimo/issues\n"+ )+ tmpio = io.StringIO()+ traceback.print_exc(file=tmpio)+ tmpio.seek(0)+ sys.stderr.write(tmpio.read())+ # Entering undefined behavior territory ...+ continue+if variable_values:VariableValues(variables=variable_values).broadcast()self._run_cells(diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex a398bf655f..3dbf400437 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -84,6 +84,18 @@ def test_set_ui_element_value(k: Kernel) -> None:assert k.globals["x"] == 6+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")])+ # _s's name is mangled to _cell_1_s because it is local+ assert k.globals["_cell_1_s"].value == 1++ element_id = k.globals["_cell_1_s"]._id+ # This shouldn't crash the kernel, and s's value should still be updated+ k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))+ assert k.globals["_cell_1_s"].value == 5++def test_creation_with_ui_element_value(k: Kernel) -> None:id_provider = IDProvider(prefix="1")k.instantiate(