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: remove any need for tornado in matplotlib.interactive (#2716)
Myles Scolnick531d84ac4710
diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.pyindex b9db6ad86d..c0824f8d39 100644--- a/marimo/_output/mpl.py+++ b/marimo/_output/mpl.py@@ -16,13 +16,13 @@ import base64import iofrom typing import Optional-import matplotlib.pyplot as plt # type: ignore-from matplotlib._pylab_helpers import Gcf # type: ignore-from matplotlib.backend_bases import ( # type: ignore+import matplotlib.pyplot as plt+from matplotlib._pylab_helpers import Gcf+from matplotlib.backend_bases import (FigureCanvasBase,FigureManagerBase,)-from matplotlib.backends.backend_agg import FigureCanvasAgg # type: ignore+from matplotlib.backends.backend_agg import FigureCanvasAggfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.mimetypes import KnownMimeType@@ -40,7 +40,7 @@ def close_figures() -> None:def _internal_show(canvas: FigureCanvasBase) -> None:buf = io.BytesIO()buf.seek(0)- canvas.figure.savefig(buf, format="png", bbox_inches="tight")+ canvas.figure.savefig(buf, format="png", bbox_inches="tight") # type: ignore[attr-defined]plt.close(canvas.figure)mimetype: KnownMimeType = "image/png"plot_bytes = base64.b64encode(buf.getvalue())@@ -53,7 +53,7 @@ def _internal_show(canvas: FigureCanvasBase) -> None:)-class FigureManager(FigureManagerBase): # type: ignore+class FigureManager(FigureManagerBase):def show(self) -> None:_internal_show(self.canvas)diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex 69e4ee8665..f6410e7f90 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -15,7 +15,7 @@ import signalimport threadingimport timefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Optional, Tuple+from typing import TYPE_CHECKING, Any, Optional, Tuple, Unionfrom marimo._output.builder import hfrom marimo._output.formatting import as_html@@ -31,6 +31,9 @@ from marimo._server.utils import find_free_portfrom marimo._utils.signals import get_signalsif TYPE_CHECKING:+ from matplotlib.axes import Axes+ from matplotlib.backends.backend_webagg_core import FigureManagerWebAgg+ from matplotlib.figure import Figurefrom starlette.applications import Starlettefrom starlette.requests import Requestfrom starlette.websockets import WebSocket@@ -38,17 +41,17 @@ if TYPE_CHECKING:class FigureManagers:def __init__(self) -> None:- self.figure_managers: dict[str, Any] = {}+ self.figure_managers: dict[str, FigureManagerWebAgg] = {}- def add(self, manager: Any) -> None:+ def add(self, manager: FigureManagerWebAgg) -> None:self.figure_managers[str(manager.num)] = manager- def get(self, figure_id: str) -> Any:+ def get(self, figure_id: str) -> FigureManagerWebAgg:if figure_id not in self.figure_managers:raise RuntimeError(f"Figure {figure_id} not found.") # noqa: E501return self.figure_managers[str(figure_id)]- def remove(self, manager: Any) -> None:+ def remove(self, manager: FigureManagerWebAgg) -> None:del self.figure_managers[str(manager.num)]@@ -71,8 +74,8 @@ def create_application(host: str,port: int,) -> Starlette:- import matplotlib as mpl # type: ignore- from matplotlib.backends.backend_webagg import ( # type: ignore+ import matplotlib as mpl+ from matplotlib.backends.backend_webagg_core import (FigureManagerWebAgg,)from starlette.applications import Starlette@@ -89,7 +92,7 @@ def create_application(async def mpl_js(request: Request) -> Response:del requestreturn Response(- content=FigureManagerWebAgg.get_javascript(), # type: ignore+ content=FigureManagerWebAgg.get_javascript(), # type: ignore[no-untyped-call]media_type="application/javascript",)@@ -127,7 +130,7 @@ def create_application(figure_id = websocket.query_params.get("figure")assert figure_id is not Nonefigure_manager = figure_managers.get(figure_id)- figure_manager.add_web_socket(SyncWebSocket())+ figure_manager.add_web_socket(SyncWebSocket()) # type: ignore[no-untyped-call]async def receive() -> None:try:@@ -139,7 +142,7 @@ def create_application(# to the figure managerpasselse:- figure_manager.handle_json(data)+ figure_manager.handle_json(data) # type: ignore[no-untyped-call]except Exception:passfinally:@@ -176,7 +179,7 @@ def create_application(Mount("/mpl/_static",StaticFiles(- directory=FigureManagerWebAgg.get_static_file_path() # type: ignore # noqa: E501+ directory=FigureManagerWebAgg.get_static_file_path() # type: ignore[no-untyped-call]),name="mpl_static",),@@ -227,8 +230,28 @@ def get_or_create_application() -> Starlette:return _app+def new_figure_manager_given_figure(+ num: int, figure: Union[Figure, Axes]+) -> Any:+ from matplotlib.backends.backend_webagg_core import (+ FigureCanvasWebAggCore,+ FigureManagerWebAgg as CoreFigureManagerWebAgg,+ NavigationToolbar2WebAgg as CoreNavigationToolbar2WebAgg,+ )++ class FigureManagerWebAgg(CoreFigureManagerWebAgg):+ _toolbar2_class = CoreNavigationToolbar2WebAgg # type: ignore[assignment]++ class FigureCanvasWebAgg(FigureCanvasWebAggCore):+ manager_class = FigureManagerWebAgg # type: ignore[assignment]++ canvas = FigureCanvasWebAgg(figure) # type: ignore[no-untyped-call]+ manager = FigureManagerWebAgg(canvas, num) # type: ignore[no-untyped-call]+ return manager++@mddoc-def interactive(figure: "Figure | Axes") -> Html: # type: ignore[name-defined] # noqa:F821,E501+def interactive(figure: Union[Figure, Axes]) -> Html:"""Render a matplotlib figure using an interactive viewer.The interactive viewer allows you to pan, zoom, and see plot coordinates@@ -252,15 +275,12 @@ def interactive(figure: "Figure | Axes") -> Html: # type: ignore[name-defined]"""# No top-level imports of matplotlib, since it isn't a required# dependency- from matplotlib.axes import ( # type: ignore[import-not-found,import-untyped,unused-ignore] # noqa: E501- Axes,- )- from matplotlib.backends.backend_webagg import ( # type: ignore- new_figure_manager_given_figure,- )+ from matplotlib.axes import Axesif isinstance(figure, Axes):- figure = figure.get_figure()+ maybe_figure = figure.get_figure()+ assert maybe_figure is not None, "Axes object does not have a Figure"+ figure = maybe_figurectx = get_context()if not isinstance(ctx, KernelRuntimeContext):diff --git a/pyproject.toml b/pyproject.tomlindex c3c5ef1496..3f51caa2e9 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -147,6 +147,7 @@ dependencies = [# Types for mypy"polars~=1.9.0","narwhals>=1.9.0",+ "matplotlib>=3.8.0","pyarrow-stubs>=17.0","pandas-stubs>=1.5.3.230321","types-Pillow~=10.2.0.20240520",diff --git a/tests/_plugins/stateless/test_mpl.py b/tests/_plugins/stateless/test_mpl.pynew file mode 100644index 0000000000..3017424fd6--- /dev/null+++ b/tests/_plugins/stateless/test_mpl.py@@ -0,0 +1,66 @@+from __future__ import annotations++from unittest.mock import patch++import pytest++from marimo._dependencies.dependencies import DependencyManager+from marimo._output.hypertext import Html+from marimo._runtime.requests import DeleteCellRequest+from marimo._runtime.runtime import Kernel+from tests.conftest import ExecReqProvider+++ not DependencyManager.matplotlib.has(),+ reason="matplotlib is not installed",+)+async def test_mpl_interactive(k: Kernel, exec_req: ExecReqProvider) -> None:+ from threading import Thread++ # This tests that the interactive figure is correctly displayed+ # and does not crash when tornado is not installed.++ with patch.object(Thread, "start", lambda self: None): # noqa: ARG005+ await k.run(+ [+ cell := exec_req.get(+ """+ # remove tornado from sys.modules+ import sys+ sys.modules.pop("tornado", None)++ import marimo as mo+ import matplotlib.pyplot as plt+ plt.plot([1, 2])+ try:+ interactive = mo.mpl.interactive(plt.gcf())+ except Exception as e:+ interactive = str(e)+ """+ ),+ ]+ )++ interactive = k.globals["interactive"]+ assert isinstance(interactive, Html)+ assert interactive.text.startswith("<iframe srcdoc=")+ await k.delete_cell(DeleteCellRequest(cell_id=cell.cell_id))+++ not DependencyManager.matplotlib.has(),+ reason="matplotlib is not installed",+)+async def test_mpl_show(k: Kernel, exec_req: ExecReqProvider) -> None:+ await k.run(+ [+ exec_req.get(+ """+ import matplotlib.pyplot as plt+ plt.plot([1, 2])+ plt.show()+ """+ )+ ]+ )