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: sync anywidget python back to frontend (#2055)
Myles Scolnick10399b326bf9
diff --git a/frontend/2043.py b/frontend/2043.pynew file mode 100644index 0000000000..af3a7509d2--- /dev/null+++ b/frontend/2043.py@@ -0,0 +1,133 @@+import marimo++__generated_with = "0.8.0"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ import anywidget+ import traitlets+ import random+ return anywidget, mo, random, traitlets++[email protected](hide_code=True)+def __(anywidget, traitlets):+ class CounterWidget(anywidget.AnyWidget):+ _esm = """+ function render({ model, el }) {+ const button = document.createElement("button");+ const update = () => {+ button.innerHTML = `${model.get("msg")} ${model.get("count")} (js-none: ${Math.random().toFixed(3)})`;+ };+ button.addEventListener("click", () => {+ model.set("count", model.get("count") + 1);+ model.save_changes();+ });+ update();+ model.on("change:count", update);+ model.on("change:msg", update);+ el.classList.add("counter-widget");+ el.appendChild(button);+ }+ export default { render };+ """+ _css = """+ .counter-widget button { color: white; font-size: 1.75rem; background-color: #ea580c; padding: 0.5rem 1rem; border: none; border-radius: 0.25rem; }+ .counter-widget button:hover { background-color: #9a3412; }+ """+ count = traitlets.Int(0).tag(sync=True)+ msg = traitlets.Unicode("").tag(sync=True)+ return CounterWidget,+++def __(mo):+ mo.md(r"""## Just anywidget""")+ return+++def __(CounterWidget):+ counter = CounterWidget(count=42, msg="count is")+ return counter,+++def __(counter):+ counter+ return+++def __(counter, mo, random):+ def _one(v):+ counter.set_trait(+ "msg", f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"+ )+++ def _two(v):+ counter.msg = f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"+++ one = mo.ui.button(label="set_trait", on_change=_one)+ two = mo.ui.button(label="counter.msg = x", on_change=_two)+ mo.hstack([one, two]).left()+ return one, two++[email protected](hide_code=True)+def __(mo):+ mo.md(r"""## Wrapped in mo.ui.anywidget""")+ return+++def __(CounterWidget, mo):+ wrapped_counter = mo.ui.anywidget(CounterWidget(count=42, msg="count is"))+ return wrapped_counter,+++def __(wrapped_counter):+ wrapped_counter+ return+++def __(mo, random, wrapped_counter):+ def _one(v):+ wrapped_counter.set_trait(+ "msg", f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"+ )+++ def _two(v):+ wrapped_counter.msg = f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"+++ def _three(v):+ wrapped_counter.widget.msg = (+ f"COUNT IS!! (py-nonce: {random.randint(0, 100)})"+ )+++ button_one = mo.ui.button(label="set_trait", on_change=_one)+ button_two = mo.ui.button(label="counter.msg = x", on_change=_two)+ button_three = mo.ui.button(label="counter.widgt.msg = x", on_change=_two)+ mo.hstack([button_one, button_two, button_three]).left()+ return button_one, button_three, button_two+++def __(wrapped_counter):+ # Should be: <class '...MarimoComm'>+ type(wrapped_counter.widget.comm)+ return+++if __name__ == "__main__":+ app.run()diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsxindex 33050f233a..865e74f7cc 100644--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx@@ -25,9 +25,7 @@ type T = Record<string, any>;// eslint-disable-next-line @typescript-eslint/consistent-type-definitionstype PluginFunctions = {- send_to_widget: <T>(req: {- content?: any;- }) => Promise<null | undefined>;+ send_to_widget: <T>(req: { content?: any }) => Promise<null | undefined>;};export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")@@ -235,7 +233,22 @@ class Model<T extends Record<string, any>> implements AnyModel<T> {* We want to notify all listeners with `msg:custom`*/receiveCustomMessage(message: any, buffers?: DataView[]): void {- this.listeners["msg:custom"]?.forEach((cb) => cb(message, buffers));+ const response = WidgetMessageSchema.safeParse(message);+ if (response.success) {+ const data = response.data;+ switch (data.method) {+ case "update":+ this.updateAndEmitDiffs(data.state as T);+ break;+ case "custom":+ this.listeners["msg:custom"]?.forEach((cb) =>+ cb(data.content, buffers),+ );+ break;+ }+ } else {+ Logger.error("Failed to parse message", message, response.error);+ }}on(eventName: string, callback: EventHandler): void {@@ -252,3 +265,14 @@ class Model<T extends Record<string, any>> implements AnyModel<T> {this.listeners[event].forEach((cb) => cb(value));}}++const WidgetMessageSchema = z.union([+ z.object({+ method: z.literal("update"),+ state: z.record(z.any()),+ }),+ z.object({+ method: z.literal("custom"),+ content: z.any(),+ }),+]);diff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex f50b60766d..130f4c8aae 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -146,6 +146,7 @@ class DependencyManager:anywidget = Dependency("anywidget")watchdog = Dependency("watchdog")ipython = Dependency("IPython")+ ipywidgets = Dependency("ipywidgets")nbformat = Dependency("nbformat")narwhals = Dependency("narwhals")ruff = Dependency("ruff")diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex 3e347e49f2..1fb27f5aab 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -317,7 +317,7 @@ class SendUIElementMessage(Op):name: ClassVar[str] = "send-ui-element-message"ui_element: str- message: JSONType+ message: Dict[str, object]buffers: Optional[Sequence[str]]diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 36b4684cc5..d7396fa2de 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -15,6 +15,7 @@ from marimo._output.formatters.df_formatters import (from marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.formatters.holoviews_formatters import HoloViewsFormatterfrom marimo._output.formatters.ipython_formatters import IPythonFormatter+from marimo._output.formatters.ipywidgets_formatters import IPyWidgetsFormatterfrom marimo._output.formatters.leafmap_formatters import LeafmapFormatterfrom marimo._output.formatters.matplotlib_formatters import MatplotlibFormatterfrom marimo._output.formatters.pandas_formatters import PandasFormatter@@ -38,6 +39,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {BokehFormatter.package_name(): BokehFormatter(),HoloViewsFormatter.package_name(): HoloViewsFormatter(),IPythonFormatter.package_name(): IPythonFormatter(),+ IPyWidgetsFormatter.package_name(): IPyWidgetsFormatter(),AnyWidgetFormatter.package_name(): AnyWidgetFormatter(),TqdmFormatter.package_name(): TqdmFormatter(),}diff --git a/marimo/_output/formatters/ipywidgets_formatters.py b/marimo/_output/formatters/ipywidgets_formatters.pynew file mode 100644index 0000000000..626fbe9e31--- /dev/null+++ b/marimo/_output/formatters/ipywidgets_formatters.py@@ -0,0 +1,17 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._output.formatters.formatter_factory import FormatterFactory+from marimo._plugins.ui._impl.anywidget.init import init_marimo_widget+++class IPyWidgetsFormatter(FormatterFactory):+ @staticmethod+ def package_name() -> str:+ return "ipywidgets"++ def register(self) -> None:+ import ipywidgets # type:ignore++ Widget = ipywidgets.Widget+ Widget.on_widget_constructed(init_marimo_widget) # type:ignorediff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 487b27ed63..2774e370b3 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -13,6 +13,7 @@ from typing import (TYPE_CHECKING,Any,Callable,+ Dict,Generic,Optional,Sequence,@@ -420,7 +421,7 @@ class UIElement(Html, Generic[S, T], metaclass=abc.ABCMeta):)def send_message(- self, message: JSONType, buffers: Optional[Sequence[bytes]]+ self, message: Dict[str, object], buffers: Optional[Sequence[bytes]]) -> None:"""Send a message to the element rendered on the frontenddiff --git a/marimo/_plugins/ui/_impl/anywidget/comm.py b/marimo/_plugins/ui/_impl/anywidget/comm.pynew file mode 100644index 0000000000..4e49a36a96--- /dev/null+++ b/marimo/_plugins/ui/_impl/anywidget/comm.py@@ -0,0 +1,176 @@+from __future__ import annotations++import base64+from typing import Any, Callable, Dict, List, Optional+++class MarimoCommManager:+ comms: Dict[str, "MarimoComm"] = {}++ def register_comm(self, comm: "MarimoComm") -> str:+ comm_id = comm.comm_id+ self.comms[comm_id] = comm+ return comm_id++ def unregister_comm(self, comm: "MarimoComm") -> "MarimoComm":+ return self.comms.pop(comm.comm_id)+++MsgCallback = Callable[[Dict[str, object]], None]+DataType = Optional[Dict[str, object]]+MetadataType = Optional[Dict[str, object]]+BufferType = Optional[List[bytes]]++COMM_MESSAGE_NAME = "marimo_comm_msg"+COMM_OPEN_NAME = "marimo_comm_open"+COMM_CLOSE_NAME = "marimo_comm_close"+++# Compare to `ipykernel.comm.Comm`+# (uses the marimo context instead of a Kernel to send/receive messages).+# Also note that `ipywidgets.widgets.Widget` is responsible to+# calling these methods when need be.+class MarimoComm:+ # `ipywidgets.widgets.Widget` does some checks for+ # `if self.comm.kernel is not None`+ kernel = "marimo"++ _msg_callback: Optional[MsgCallback]+ _close_callback: Optional[MsgCallback]+ _closed: bool = False+ _closed_data: Dict[str, object] = {}++ def __init__(+ self,+ comm_id: str,+ comm_manager: MarimoCommManager,+ target_name: str,+ data: DataType = None,+ metadata: MetadataType = None,+ buffers: BufferType = None,+ **keys: object,+ ) -> None:+ self.comm_id = comm_id+ self.comm_manager = comm_manager+ self.target_name = target_name+ self.open(data=data, metadata=metadata, buffers=buffers, **keys)+ self.ui_element_id: Optional[str] = None+ self._publish_message_buffer: list[Any] = []++ def open(+ self,+ data: DataType = None,+ metadata: MetadataType = None,+ buffers: BufferType = None,+ **keys: object,+ ) -> None:+ self.comm_manager.register_comm(self)+ try:+ self._publish_msg(+ COMM_OPEN_NAME,+ data=data,+ metadata=metadata,+ buffers=buffers,+ target_name=self.target_name,+ target_module=None,+ **keys,+ )+ self._closed = False+ except Exception:+ self.comm_manager.unregister_comm(self)+ raise++ # Inform client of any mutation(s) to the model+ # (e.g., add a marker to a map, without a full redraw)+ def send(+ self,+ data: DataType = None,+ metadata: MetadataType = None,+ buffers: BufferType = None,+ ) -> None:+ self._publish_msg(+ COMM_MESSAGE_NAME,+ data=data,+ metadata=metadata,+ buffers=buffers,+ )++ def close(+ self,+ data: DataType = None,+ metadata: MetadataType = None,+ buffers: BufferType = None,+ deleting: bool = False,+ ) -> None:+ if self._closed:+ return+ self._closed = True+ data = self._closed_data if data is None else data+ self._publish_msg(+ COMM_CLOSE_NAME,+ data=data,+ metadata=metadata,+ buffers=buffers,+ )+ if not deleting:+ # If deleting, the comm can't be unregistered+ self.comm_manager.unregister_comm(self)++ # trigger close on gc+ def __del__(self) -> None:+ self.close(deleting=True)++ # Compare to `ipykernel.comm.Comm._publish_msg`, but...+ # https://github.com/jupyter/jupyter_client/blob/c5c0b80/jupyter_client/session.py#L749+ # ...the real meat of the implement+ # is in `jupyter_client.session.Session.send`+ # https://github.com/jupyter/jupyter_client/blob/c5c0b8/jupyter_client/session.py#L749-L862+ def _publish_msg(+ self,+ msg_type: str,+ data: DataType = None,+ metadata: MetadataType = None,+ buffers: BufferType = None,+ **keys: object,+ ) -> None:+ del keys+ data = {} if data is None else data+ metadata = {} if metadata is None else metadata+ buffers = [] if buffers is None else buffers++ if msg_type == COMM_MESSAGE_NAME:+ self._publish_message_buffer.append((data, metadata, buffers))+ self.flush()++ def flush(self) -> None:+ if not self.ui_element_id:+ return++ from marimo._messaging.ops import SendUIElementMessage++ while self._publish_message_buffer:+ data, _metadata, buffers = self._publish_message_buffer.pop(0)++ SendUIElementMessage(+ ui_element=self.ui_element_id,+ message=data,+ buffers=[+ base64.b64encode(buffer).decode() for buffer in buffers+ ],+ ).broadcast()++ # This is the method that ipywidgets.widgets.Widget uses to respond to+ # client-side changes+ def on_msg(self, callback: MsgCallback) -> None:+ self._msg_callback = callback++ def on_close(self, callback: MsgCallback) -> None:+ self._close_callback = callback++ def handle_msg(self, msg: Dict[str, object]) -> None:+ if self._msg_callback is not None:+ self._msg_callback(msg)++ def handle_close(self, msg: Dict[str, object]) -> None:+ if self._close_callback is not None:+ self._close_callback(msg)diff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.pynew file mode 100644index 0000000000..2d4dab2c99--- /dev/null+++ b/marimo/_plugins/ui/_impl/anywidget/init.py@@ -0,0 +1,45 @@+from __future__ import annotations++from typing import TYPE_CHECKING, cast+from uuid import uuid4++if TYPE_CHECKING:+ import ipywidgets # type: ignore++from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._impl.anywidget.comm import ( # pyright: ignore[reportMissingTypeStubs]+ BufferType,+ MarimoComm,+ MarimoCommManager,+)+++# Initialize ipywidgets using a MarimoComm+def init_marimo_widget(w: "ipywidgets.Widget") -> None:+ DependencyManager.ipywidgets.require("for anywidget support.")+ import ipywidgets # type: ignore++ __protocol_version__ = ipywidgets._version.__protocol_version__+ _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore++ # Get the initial state of the widget+ state, buffer_paths, buffers = _remove_buffers(w.get_state()) # type: ignore++ # Generate a random model_id so we can assign the same id to the comm+ if getattr(w, "_model_id", None) is None:+ w._model_id = uuid4().hex++ # Initialize the comm...this will also send the initial state of the widget+ w.comm = MarimoComm(+ comm_id=w._model_id, # pyright: ignore+ comm_manager=COMM_MANAGER,+ target_name="jupyter.widgets",+ data={"state": state, "buffer_paths": buffer_paths},+ buffers=cast(BufferType, buffers),+ # TODO: should this be hard-coded?+ metadata={"version": __protocol_version__},+ # html_deps=session._process_ui(TagList(widget_dep))["deps"],+ )+++COMM_MANAGER = MarimoCommManager()diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex ca548d1583..462c0e9430 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -10,7 +10,8 @@ import marimo._output.data.data as mo_datafrom marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.json_encoder import WebComponentEncoder-from marimo._plugins.ui._core.ui_element import UIElement+from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement+from marimo._plugins.ui._impl.anywidget.comm import MarimoCommfrom marimo._runtime.functions import Functionif TYPE_CHECKING:@@ -78,6 +79,8 @@ class anywidget(UIElement[T, T]):def __init__(self, widget: "AnyWidget"):self.widget = widget+ # This gets set to True in super().__init__()+ self._initialized = False# Get all the traits of the widgetargs: T = widget.trait_values()@@ -122,8 +125,6 @@ class anywidget(UIElement[T, T]):js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore] # noqa: E501css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501- self.widget.comm = _maybe_create_comm(self)-super().__init__(component_name="marimo-anywidget",initial_value=json_args,@@ -142,10 +143,17 @@ class anywidget(UIElement[T, T]):),)- def _send_to_frontend(- self, value: T, buffers: Optional[Any] = None+ def _initialize(+ self,+ initialization_args: InitializationArgs[+ Dict[str, Any], Dict[str, Any]+ ],) -> None:- self.send_message(value, buffers)+ super()._initialize(initialization_args)+ # Add the ui_element_id after the widget is initialized+ comm = self.widget.comm+ if isinstance(comm, MarimoComm):+ comm.ui_element_id = self._iddef _receive_from_frontend(self, args: SendToWidgetArgs) -> None:self.widget._handle_custom_msg(args.content, args.buffers)@@ -153,36 +161,19 @@ class anywidget(UIElement[T, T]):def _convert_value(self, value: T) -> T:return value- # Proxy all the widget's attributes+ # After the widget has been initialized+ # forward all setattr to the widget+ def __setattr__(self, name: str, value: Any) -> None:+ if self._initialized:+ return setattr(self.widget, name, value)+ return super().__setattr__(name, value)++ # After the widget has been initialized+ # forward all getattr to the widgetdef __getattr__(self, name: str) -> Any:+ if name in ("widget", "_initialized"):+ try:+ return self.__getattribute__(name)+ except AttributeError:+ return Nonereturn getattr(self.widget, name)---def _maybe_create_comm(widget: "anywidget") -> Any:- try:- from comm.base_comm import BaseComm # type: ignore-- class MarimoComm(BaseComm): # type: ignore- def publish_msg(- self,- msg_type: str,- data: Any = None,- metadata: Any = None,- buffers: Any = None,- **keys: Any,- ) -> None:- del metadata- del keys- if (- msg_type == "comm_msg"- and "method" in data- and data["method"] == "custom"- ):- if "content" in data:- widget._send_to_frontend(data["content"], buffers)- else:- LOGGER.warning("No content in custom message")-- return MarimoComm()- except ImportError:- LOGGER.warning("Comm is not available")diff --git a/marimo/_smoke_tests/anywidget/maplibre.py b/marimo/_smoke_tests/anywidget/maplibre_example.pysimilarity index 98%rename from marimo/_smoke_tests/anywidget/maplibre.pyrename to marimo/_smoke_tests/anywidget/maplibre_example.pyindex 994aaca3db..c1bb5b7a06 100644--- a/marimo/_smoke_tests/anywidget/maplibre.py+++ b/marimo/_smoke_tests/anywidget/maplibre_example.py@@ -1,7 +1,8 @@# Copyright 2024 Marimo. All rights reserved.+import marimo-__generated_with = "0.7.2"+__generated_with = "0.8.0"app = marimo.App(width="medium")diff --git a/marimo/_smoke_tests/anywidget/mosaic.py b/marimo/_smoke_tests/anywidget/mosaic_example.pysimilarity index 100%rename from marimo/_smoke_tests/anywidget/mosaic.pyrename to marimo/_smoke_tests/anywidget/mosaic_example.pydiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex 341db3de7e..c1a4763af1 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -111,3 +111,39 @@ x = as_marimo_element.countassert isinstance(k.globals["w"], anywidget)assert k.globals["w_value"]["count"] == 10assert k.globals["w_count"] == 10++ @staticmethod+ async def test_getters_setters() -> None:+ # Test on wrapped+ wrapped = anywidget(CounterWidget())+ assert wrapped.count == 0+ wrapped.count = 10+ assert wrapped.count == 10++ # Test on wrapped, with initialization+ wrapped = anywidget(CounterWidget(count=5))+ assert wrapped.count == 5+ wrapped.count = 10+ assert wrapped.count == 10++ # Test on wrapped.widget, with initialization+ wrapped = anywidget(CounterWidget(count=7))+ assert wrapped.widget.count == 7 # type: ignore+ wrapped.widget.count = 10 # type: ignore+ assert wrapped.count == 10++ assert wrapped._initialized is True++ @staticmethod+ async def test_set_trait() -> None:+ # Test on wrapped+ wrapped = anywidget(CounterWidget())+ assert wrapped.count == 0+ wrapped.set_trait("count", 10)+ assert wrapped.count == 10+ assert wrapped.widget.count == 10 # type: ignore+ wrapped.widget.set_trait("count", 7)+ assert wrapped.count == 7+ assert wrapped.widget.count == 7 # type: ignore++ assert wrapped._initialized is True