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: plotly-resampler (and other FigureWidget subclasses) not working in marimo by routing `FigureWidget` through the anywidget formatter and syncing widget state via `_repr_mimebundle_()`. (#8430)
Myles Scolnick72ab933dd88a
diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.pyindex 309fde73a3..8811f49eae 100644--- a/marimo/_output/formatters/plotly_formatters.py+++ b/marimo/_output/formatters/plotly_formatters.py@@ -42,7 +42,6 @@ class PlotlyFormatter(FormatterFactory):return ("text/html", plugin.text)@formatting.formatter(plotly.graph_objects.Figure)- @formatting.formatter(plotly.graph_objects.FigureWidget)def _plotly_formatter(fig: plotly.graph_objects.Figure,) -> tuple[KnownMimeType, str]:diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex c5ca989686..aa81b4fd4a 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -15,11 +15,13 @@ from typing import (import marimo._output.data.data as mo_datafrom marimo import _loggers+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.rich_help import mddocfrom marimo._plugins.ui._core.ui_element import InitializationArgs, UIElementfrom marimo._plugins.ui._impl.comm import MarimoCommfrom marimo._types.ids import WidgetModelIdfrom marimo._utils.code import hash_code+from marimo._utils.methods import getcallableAnyWidgetState: TypeAlias = dict[str, Any]@@ -87,6 +89,28 @@ def from_anywidget(widget: AnyWidget) -> UIElement[Any, Any]:return el+def _sync_widget_state(widget: AnyWidget) -> None:+ """Call _repr_mimebundle_ to sync widget state if available.++ Plotly's FigureWidget (and subclasses like plotly-resampler's+ FigureWidgetResampler) maintain a split internal model: the figure's+ data lives in _data/_layout_obj, but the widget traits (_widget_data,+ _widget_layout) are only updated during _repr_mimebundle_(). This call+ ensures the widget traits reflect the current figure state before the+ comm sends state to the frontend.+ """+ repr_mimebundle = getcallable(widget, "_repr_mimebundle_")+ if repr_mimebundle is not None:+ try:+ repr_mimebundle()+ except Exception:+ # Not critical — widget may still work without this sync+ LOGGER.debug(+ "Failed to call _repr_mimebundle_ on %s",+ type(widget).__name__,+ )++def get_anywidget_state(widget: AnyWidget) -> AnyWidgetState:"""Get the state of an AnyWidget."""# Remove widget-specific system traits not needed for the frontend@@ -198,6 +222,38 @@ class anywidget(UIElement[ModelIdRef, AnyWidgetState]):if isinstance(comm, MarimoComm):comm.ui_element_id = self._id+ def _ensure_widget_synced(self) -> None:+ """Sync widget state lazily on first access (idempotent).++ Some widgets (e.g. plotly FigureWidget, plotly-resampler) only sync+ their internal data to widget traits during _repr_mimebundle_().+ This ensures the sync happens once, the first time the element is+ rendered.++ NOTE: @once cannot be used here because Html is a @dataclass with+ eq=True/frozen=False, making instances unhashable (WeakKeyDictionary+ requires hashable keys).++ NOTE: If you are a widget author and need to sync state from your+ widget, do not do this in the repr_mimebundle method.+ This is not a supported pattern and may break in the future.+ """+ # Use object.__dict__ directly to bypass anywidget's+ # custom __getattr__/__setattr__+ if self.__dict__.get("_widget_synced", False):+ return+ object.__setattr__(self, "_widget_synced", True)+ _sync_widget_state(self.widget)++ @property+ def text(self) -> str:+ self._ensure_widget_synced()+ return super().text++ def _mime_(self) -> tuple[KnownMimeType, str]:+ self._ensure_widget_synced()+ return super()._mime_()+def _convert_value(self, value: ModelIdRef | AnyWidgetState) -> AnyWidgetState:diff --git a/marimo/_smoke_tests/plotly/_plotly_resampler.py b/marimo/_smoke_tests/plotly/_plotly_resampler.pyindex dbac0a8a9f..46d5992ef6 100644--- a/marimo/_smoke_tests/plotly/_plotly_resampler.py+++ b/marimo/_smoke_tests/plotly/_plotly_resampler.py@@ -14,7 +14,7 @@import marimo-__generated_with = "0.19.11"+__generated_with = "0.20.2"app = marimo.App(width="medium")@@ -48,7 +48,11 @@ def _():fig = px.scatter(df, x="x", y="y", color="color", title="Scatter Plot with 1M Datapoints")+ return (fig,)++def _(fig):figreturndiff --git a/tests/_output/formatters/test_plotly_formatters.py b/tests/_output/formatters/test_plotly_formatters.pyindex be48358e24..83425ac2c2 100644--- a/tests/_output/formatters/test_plotly_formatters.py+++ b/tests/_output/formatters/test_plotly_formatters.py@@ -7,8 +7,10 @@ import pytestfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.formatters.formatters import register_formattersfrom marimo._output.formatters.plotly_formatters import PlotlyFormatter+from marimo._output.formatting import get_formatterHAS_DEPS = DependencyManager.plotly.has()+HAS_ANYWIDGET = DependencyManager.anywidget.has()@pytest.mark.skipif(not HAS_DEPS, reason="plotly not installed")@@ -31,3 +33,35 @@ def test_plotly_config_forwarding():assert "data-config=" in result.textassert "displayModeBar" in result.textassert "responsive" in result.text+++ not (HAS_DEPS and HAS_ANYWIDGET),+ reason="plotly and anywidget not installed",+)+def test_plotly_figure_widget_uses_anywidget_formatter():+ """Test that FigureWidget uses the anywidget formatter, not the static+ plotly formatter.++ FigureWidget is an anywidget.AnyWidget subclass and should go through+ the anywidget formatter path for interactive widget features (like+ plotly-resampler's dynamic resampling) to work.++ Regression test for https://github.com/marimo-team/marimo/issues/4091+ """+ register_formatters()++ import plotly.graph_objects as go++ fig_widget = go.FigureWidget(data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])])++ # get_formatter walks the MRO; for FigureWidget, the first match+ # should be the anywidget formatter (not the plotly Figure formatter)+ formatter = get_formatter(fig_widget)+ assert formatter is not None++ # Call the formatter and verify it goes through the anywidget path+ mimetype, data = formatter(fig_widget)+ assert mimetype == "text/html"+ assert "marimo-anywidget" in data+ assert "marimo-plotly" not in datadiff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.pyindex 10aee85307..c4e49839a2 100644--- a/tests/_plugins/ui/_impl/test_anywidget.py+++ b/tests/_plugins/ui/_impl/test_anywidget.py@@ -27,6 +27,7 @@ from tests.conftest import ExecReqProviderHAS_DEPS = (DependencyManager.anywidget.has() and DependencyManager.traitlets.has())+HAS_PLOTLY = DependencyManager.plotly.has()if HAS_DEPS:import anywidget as _anywidget@@ -732,3 +733,38 @@ run_count = globals().get("run_count", 0) + 1assert k.globals["result"] == 7# The defining cell should NOT have re-run (no self-loop)assert k.globals["run_count"] == initial_run_count++ @staticmethod+ @pytest.mark.skipif(not HAS_PLOTLY, reason="plotly not installed")+ async def test_plotly_figure_widget_uses_anywidget_path(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ """Test that plotly FigureWidget is rendered via the anywidget path.++ FigureWidget is an anywidget.AnyWidget subclass and must go through+ the widget comm path (not static plotly rendering) for interactive+ features like plotly-resampler's dynamic resampling to work.++ Regression test for https://github.com/marimo-team/marimo/issues/4091+ """+ await k.run(+ [+ exec_req.get(+ """+import plotly.graph_objects as go+import marimo as mo++fig = go.FigureWidget(+ data=[go.Scatter(x=[1, 2, 3], y=[4, 5, 6])]+)+html_output = mo.as_html(fig).text+uses_anywidget = "marimo-anywidget" in html_output+uses_static_plotly = "marimo-plotly" in html_output+"""+ )+ ]+ )+ # FigureWidget should use the anywidget path+ assert k.globals["uses_anywidget"] is True+ # FigureWidget should NOT use the static plotly path+ assert k.globals["uses_static_plotly"] is False