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: merge anywidget partial updates (#3745)
Myles Scolnick5e76fa6e5bcb
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex c53bdf71be..1df4b74459 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -107,6 +107,7 @@ class anywidget(UIElement[T, T]):# Remove ignored traitsfor trait_name in ignored_traits:args.pop(trait_name, None)+# Keep only classes that are json serialize-ablejson_args: T = {}for k, v in args.items():@@ -137,9 +138,11 @@ class anywidget(UIElement[T, T]):js.encode("utf-8"), usedforsecurity=False).hexdigest()+ self._prev_state = json_args+super().__init__(component_name="marimo-anywidget",- initial_value=json_args,+ initial_value=self._prev_state,label="",args={"js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore] # noqa: E501@@ -173,6 +176,11 @@ class anywidget(UIElement[T, T]):self.widget._handle_custom_msg(args.content, args.buffers)def _convert_value(self, value: T) -> T:+ if isinstance(value, dict) and isinstance(self._prev_state, dict):+ merged = {**self._prev_state, **value}+ self._prev_state = merged+ return merged+ self._prev_state = valuereturn value# After the widget has been initializeddiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex b4b0091382..f0f4352a8a 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -237,7 +237,8 @@ x = as_marimo_element.count) -> None:await k.run([- exec_req.get("""+ exec_req.get(+ """import marimo as moimport traitletsimport anywidget as _anywidget@@ -247,7 +248,8 @@ x = as_marimo_element.countvalue = traitlets.Int(0).tag(sync=True)w = mo.ui.anywidget(TestWidget())- """)+ """+ )])@@ -331,3 +333,46 @@ x = as_marimo_element.countwrapped2._component_args["js-hash"]!= wrapped._component_args["js-hash"])++ @staticmethod+ def test_state_merging() -> None:+ class StateWidget(_anywidget.AnyWidget):+ _esm = ""+ a = traitlets.Int(1, allow_none=True).tag(sync=True)+ b = traitlets.Int(2).tag(sync=True)++ wrapped = anywidget(StateWidget())+ assert wrapped.value == {"a": 1, "b": 2}++ # Test partial update merges with existing state+ wrapped._update({"a": 10})+ assert wrapped.value == {"a": 10, "b": 2}++ # Test multiple updates maintain merged state+ wrapped._update({"b": 20})+ assert wrapped.value == {"a": 10, "b": 20}++ # Test unsetting a trait+ wrapped._update({"a": None})+ assert wrapped.value == {"b": 20, "a": None}++ @staticmethod+ def test_state_persistence() -> None:+ class PersistWidget(_anywidget.AnyWidget):+ _esm = ""+ x = traitlets.Int(0).tag(sync=True)+ y = traitlets.Dict().tag(sync=True)++ wrapped = anywidget(PersistWidget())+ initial_state = {"x": 0, "y": {}}+ assert wrapped.value == initial_state++ # Update with partial state+ new_state = {"x": 42}+ wrapped._update(new_state)+ assert wrapped.value == {"x": 42, "y": {}}++ # Update nested state+ nested_state = {"y": {"key": "value"}}+ wrapped._update(nested_state)+ assert wrapped.value == {"x": 42, "y": {"key": "value"}}