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: patch polars write_json in wasm with write_csv (#4895)
Myles Scolnick28b12151ef84
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.pyindex 971f22371b..bc0dc69e17 100644--- a/marimo/_output/formatters/df_formatters.py+++ b/marimo/_output/formatters/df_formatters.py@@ -7,10 +7,14 @@ import narwhals.stable.v1 as nwfrom marimo import _loggersfrom marimo._messaging.mimetypes import KnownMimeType-from marimo._output.formatters.formatter_factory import FormatterFactory+from marimo._output.formatters.formatter_factory import (+ FormatterFactory,+ Unregister,+)from marimo._output.md import mdfrom marimo._plugins.ui._impl import tabsfrom marimo._plugins.ui._impl.table import get_default_table_page_size, table+from marimo._runtime.patches import patch_polars_write_jsonLOGGER = _loggers.marimo_logger()@@ -35,13 +39,15 @@ class PolarsFormatter(FormatterFactory):def package_name() -> str:return "polars"- def register(self) -> None:+ def register(self) -> Unregister | None:import polars as plfrom marimo._output import formattingif not include_opinionated():- return+ return None++ unpatch_polars_write_json = patch_polars_write_json()@formatting.opinionated_formatter(pl.DataFrame)def _show_marimo_dataframe(@@ -79,6 +85,8 @@ class PolarsFormatter(FormatterFactory):})._mime_()+ return unpatch_polars_write_json+class PyArrowFormatter(FormatterFactory):@staticmethoddiff --git a/marimo/_output/formatters/formatter_factory.py b/marimo/_output/formatters/formatter_factory.pyindex a347117b0b..3eb985ead7 100644--- a/marimo/_output/formatters/formatter_factory.py+++ b/marimo/_output/formatters/formatter_factory.py@@ -9,6 +9,8 @@ from marimo._config.config import ThemeLOGGER = _loggers.marimo_logger()+Unregister = Callable[[], None]+# Abstract base class for formatters that are installed at runtime.class FormatterFactory(abc.ABC):@@ -25,7 +27,7 @@ class FormatterFactory(abc.ABC):raise NotImplementedError@abc.abstractmethod- def register(self) -> Callable[[], None] | None:+ def register(self) -> Unregister | None:"""Registers formatters.Formatters can be registered using the formatters.formatter decorator.diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex 287bea586c..b45b4f2702 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -10,6 +10,9 @@ from typing import TYPE_CHECKING, Any, Callablefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime import marimo_browser, marimo_pdb+from marimo._utils.platform import is_pyodide++Unpatch = Callable[[], None]if TYPE_CHECKING:from collections.abc import Iterator@@ -419,3 +422,72 @@ def patch_jedi_parameter_completion() -> None:SignatureParamName.infer = wrap_infer(original_dynamic_infer)if not getattr(SignatureParamName.__init__, "patched", False):SignatureParamName.__init__ = enhanced_init+++def patch_polars_write_json() -> Unpatch:+ """Patch polars.DataFrame.write_json to work in WASM environments.++ In WASM, file system operations may fail. This patch attempts to use+ write_json first, and if it fails, falls back to write_csv and then+ converts the CSV to JSON.+ """+ if not is_pyodide():+ return lambda: None++ import io+ import pathlib++ import polars++ original_write_json = polars.DataFrame.write_json++ def patched_write_json(+ self: polars.DataFrame,+ file: io.IOBase | str | pathlib.Path | None = None,+ *args: Any,+ **kwargs: Any,+ ) -> str | None:+ try:+ # First try the original method+ return original_write_json(self, file, *args, **kwargs)+ except Exception:+ # Fallback to CSV+ import json++ buffer = io.BytesIO()++ # Write to CSV+ self.write_csv(buffer)++ # Read CSV as text+ buffer.seek(0)+ csv_content = buffer.read().decode("utf-8")++ # Parse CSV to create JSON+ lines = csv_content.strip().split("\n")+ json_data: list[dict[str, str]] = []+ if lines:+ headers: list[str] = lines[0].split(",")+ for line in lines[1:]:+ values: list[str] = line.split(",")+ json_data.append(dict(zip(headers, values)))++ if file is None:+ return json.dumps(json_data)+ elif isinstance(file, io.IOBase):+ json.dump(json_data, file)+ elif isinstance(file, pathlib.Path):+ file.write_text(json.dumps(json_data))+ else:+ with open(file, "w", encoding="utf-8") as f:+ json.dump(json_data, f)++ return None++ # Apply the patch+ polars.DataFrame.write_json = patched_write_json # type: ignore++ def unpatch_polars_write_json() -> None:+ polars.DataFrame.write_json = original_write_json # type: ignore++ return unpatch_polars_write_jsondiff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.pyindex ca615474d4..0d0200f9e5 100644--- a/tests/_runtime/test_patches.py+++ b/tests/_runtime/test_patches.py@@ -1,11 +1,23 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import io+from types import ModuleType+from typing import TYPE_CHECKING+from unittest.mock import patch++import pytest++from marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime.capture import capture_stderr+from marimo._runtime.patches import patch_polars_write_jsonfrom marimo._runtime.runtime import Kernelfrom marimo._utils.platform import is_pyodidefrom tests.conftest import ExecReqProvider+if TYPE_CHECKING:+ from pathlib import Path+class TestMicropip:@staticmethod@@ -175,3 +187,59 @@ async def test_webbrowser_easter_egg(assert "<iframe" not in outputs[-1]assert "<img" in outputs[-1]+++ not DependencyManager.polars.has(),+ reason="Polars is not installed",+)+def test_polars_write_json_patch(tmp_path: Path):+ import sys++ import polars as pl++ file_path = tmp_path / "test.json"++ # Fake put pyodide in sys.modules+ sys.modules["pyodide"] = ModuleType("pyodide")++ # Make write_json throw an error+ with patch(+ "polars.DataFrame.write_json",+ side_effect=ValueError("Test error"),+ ):+ # Test it fails+ df = pl.DataFrame({"a": [1, 2], "b": ["x", "y"]})+ with pytest.raises(ValueError, match="Test error"):+ df.write_json(file_path)++ # Patch to fallback to write_csv+ unpatch_polars_write_json = patch_polars_write_json()++ expected_json = '[{"a": "1", "b": "x"}, {"a": "2", "b": "y"}]'++ # Test it succeeds with file path+ df.write_json(file_path)+ assert file_path.read_text() == expected_json++ # Test it succeeds with string path+ df.write_json(str(file_path))+ assert file_path.read_text() == expected_json++ # Test it succeeds with buffer+ buffer = io.StringIO()+ df.write_json(buffer)+ assert buffer.getvalue() == expected_json++ # Test it succeeds with None+ assert df.write_json() == expected_json++ # Patch the patch+ unpatch_polars_write_json()++ # Test it fails again+ with pytest.raises(ValueError, match="Test error"):+ df.write_json(file_path)++ # Remove pyodide from sys.modules+ del sys.modules["pyodide"]