Skip to content

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.

improvement: support nested polars data in mo.ui.table, support polars > 1.0 (#1830)

Myles Scolnickfdc605356c4d
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index a5f271c646..ae3868064f 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -1,10 +1,13 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from marimo import _loggers
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._plugins.ui._impl.table import table
+LOGGER = _loggers.marimo_logger()
+
class PolarsFormatter(FormatterFactory):
@staticmethod
@@ -20,16 +23,11 @@ class PolarsFormatter(FormatterFactory):
def _show_marimo_dataframe(
df: pl.DataFrame,
) -> tuple[KnownMimeType, str]:
- # If has structured don't display in the table
- for col in df.get_columns():
- if (
- col.dtype == pl.Struct
- or col.dtype == pl.List
- or col.dtype == pl.Array
- ):
- return ("text/html", df._repr_html_())
-
- return table(df, selection=None, pagination=True)._mime_()
+ try:
+ return table(df, selection=None, pagination=True)._mime_()
+ except Exception as e:
+ LOGGER.warning("Failed to format DataFrame: %s", e)
+ return ("text/html", df._repr_html_())
class PyArrowFormatter(FormatterFactory):
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 755a5eda0d..384302cb73 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -30,10 +30,46 @@ class PolarsTableManagerFactory(TableManagerFactory):
type = "polars"
def to_csv(self) -> bytes:
- return self.data.write_csv().encode("utf-8")
+ try:
+ return self.data.write_csv().encode("utf-8")
+ except pl.exceptions.ComputeError:
+ # Likely CSV format does not support nested data or objects
+ # Try to convert columns to json or strings
+ result = self.data
+ for column in result.get_columns():
+ if column.dtype == pl.Struct:
+ result = result.with_columns(
+ column.struct.json_encode()
+ )
+ elif column.dtype == pl.List:
+ result = result.with_columns(
+ column.cast(pl.List(pl.Utf8)).list.join(",")
+ )
+ elif column.dtype == pl.Array:
+ result = result.with_columns(
+ column.cast(pl.Array(pl.Utf8)).arr.join(",")
+ )
+ elif column.dtype == pl.Object:
+ result = result.with_columns(column.cast(str))
+ elif column.dtype == pl.Duration:
+ dtype = cast(pl.Duration, column.dtype)
+ if dtype.time_unit == "ns":
+ result = result.with_columns(
+ column.dt.total_nanoseconds()
+ )
+ if dtype.time_unit == "us":
+ result = result.with_columns(
+ column.dt.total_microseconds()
+ )
+ if dtype.time_unit == "ms":
+ result = result.with_columns(
+ column.dt.total_milliseconds()
+ )
+
+ return result.write_csv().encode("utf-8")
def to_json(self) -> bytes:
- return self.data.write_json(row_oriented=True).encode("utf-8")
+ return self.data.write_json().encode("utf-8")
def supports_filters(self) -> bool:
return True
@@ -156,7 +192,10 @@ class PolarsTableManagerFactory(TableManagerFactory):
def _get_field_type(
column: pl.Series,
) -> Tuple[FieldType, ExternalDataType]:
- dtype_string = column.dtype._string_repr()
+ try:
+ dtype_string = column.dtype._string_repr()
+ except (TypeError, AttributeError):
+ dtype_string = str(column.dtype)
if column.dtype == pl.String:
return ("string", dtype_string)
elif column.dtype == pl.Boolean:
diff --git a/marimo/_smoke_tests/polars/polars_to_csv.py b/marimo/_smoke_tests/polars/polars_to_csv.py
new file mode 100644
index 0000000000..a958ada821
--- /dev/null
+++ b/marimo/_smoke_tests/polars/polars_to_csv.py
@@ -0,0 +1,67 @@
+import marimo
+
+__generated_with = "0.7.8"
+app = marimo.App(width="medium")
+
+
+def __():
+ import datetime
+ import marimo as mo
+ import polars as pl
+
+ complex_data = pl.DataFrame(
+ {
+ "strings": ["a", "b", "c"],
+ "bool": [True, False, True],
+ "int": [1, 2, 3],
+ "float": [1.0, 2.0, 3.0],
+ "datetime": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "struct": [
+ {"a": 1, "b": 2},
+ {"a": 3, "b": 4},
+ {"a": 5, "b": 6},
+ ],
+ "list": [[1, 2], [3, 4], [5, 6]],
+ "array": [[1, 2, 3], [4], []],
+ "nulls": [None, "data", None],
+ "categorical": pl.Series(["cat", "dog", "mouse"]).cast(pl.Categorical),
+ "time": [
+ datetime.time(12, 30),
+ datetime.time(13, 45),
+ datetime.time(14, 15),
+ ],
+ "duration": [
+ datetime.timedelta(days=1),
+ datetime.timedelta(days=2),
+ datetime.timedelta(days=3),
+ ],
+ "mixed_list": [
+ [1, "two"],
+ [3.0, False],
+ [None, datetime.datetime(2021, 1, 1)],
+ ],
+ },
+ strict=False,
+ )
+ return complex_data, datetime, mo, pl
+
+
+def __(complex_data, mo):
+ mo.plain(complex_data)
+ return
+
+
+def __(complex_data):
+ complex_data
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/pyproject.toml b/pyproject.toml
index 0c39e0a39f..a705c1312c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -88,9 +88,7 @@ dev = [
# For testing mo.image
"pillow~=10.2.0",
"types-Pillow~=10.2.0.20240311",
- # polars 0.19.13 requires building maturn from source, but we don't
- # have the rust toolchain installed on CI
- "polars==0.20.30",
+ "polars~=1.2.0",
"pytest~=7.4.0",
"pytest-codecov~=0.5.1",
"pytest-asyncio~=0.23.4",
@@ -130,9 +128,7 @@ testoptional = [
"pyarrow-stubs>=10",
"pillow~=10.2.0",
"types-Pillow~=10.2.0.20240311",
- # polars 0.19.13 requires building maturn from source, but we don't
- # have the rust toolchain installed on CI
- "polars==0.20.30",
+ "polars~=1.2.0",
"anywidget~=0.9.3",
"ipython~=8.12.3",
"openai~=1.12.0",
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
new file mode 100644
index 0000000000..b65fb34f03
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
@@ -0,0 +1,4 @@
+strings,bool,int,float,datetime,struct,list,array,nulls,categorical,duration,mixed_list
+a,true,1,1.0,2021-01-01T00:00:00.000000,"{""a"":1,""b"":2}","1,2","1,2,3",,cat,86400000000,"1,two"
+b,false,2,2.0,2021-01-02T00:00:00.000000,"{""a"":3,""b"":4}","3,4",4,data,dog,172800000000,"3.0,0.0"
+c,true,3,3.0,2021-01-03T00:00:00.000000,"{""a"":5,""b"":6}","5,6","",,mouse,259200000000,2021-01-01 00:00:00.000000
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
new file mode 100644
index 0000000000..7c8047c5ad
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
@@ -0,0 +1,14 @@
+{
+ "strings": ["string", "str"],
+ "bool": ["boolean", "bool"],
+ "int": ["integer", "i64"],
+ "float": ["number", "f64"],
+ "datetime": ["date", "datetime[\u03bcs]"],
+ "struct": ["unknown", "struct[2]"],
+ "list": ["unknown", "list[i64]"],
+ "array": ["unknown", "list[i64]"],
+ "nulls": ["string", "str"],
+ "categorical": ["unknown", "cat"],
+ "duration": ["date", "duration[\u03bcs]"],
+ "mixed_list": ["unknown", "list[str]"]
+}
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
new file mode 100644
index 0000000000..7d5f1be8b4
--- /dev/null
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
@@ -0,0 +1,44 @@
+[
+ {
+ "strings": "a",
+ "bool": true,
+ "int": 1,
+ "float": 1.0,
+ "datetime": "2021-01-01 00:00:00",
+ "struct": { "a": 1, "b": 2 },
+ "list": [1, 2],
+ "array": [1, 2, 3],
+ "nulls": null,
+ "categorical": "cat",
+ "duration": "PT86400S",
+ "mixed_list": ["1", "two"]
+ },
+ {
+ "strings": "b",
+ "bool": false,
+ "int": 2,
+ "float": 2.0,
+ "datetime": "2021-01-02 00:00:00",
+ "struct": { "a": 3, "b": 4 },
+ "list": [3, 4],
+ "array": [4],
+ "nulls": "data",
+ "categorical": "dog",
+ "duration": "PT172800S",
+ "mixed_list": ["3.0", "0.0"]
+ },
+ {
+ "strings": "c",
+ "bool": true,
+ "int": 3,
+ "float": 3.0,
+ "datetime": "2021-01-03 00:00:00",
+ "struct": { "a": 5, "b": 6 },
+ "list": [5, 6],
+ "array": [],
+ "nulls": null,
+ "categorical": "mouse",
+ "duration": "PT259200S",
+ "mixed_list": [null, "2021-01-01 00:00:00.000000"]
+ }
+]
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index d93184ab4d..076d7288ea 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -1,7 +1,9 @@
from __future__ import annotations
import datetime
+import json
import unittest
+from typing import Any
import pytest
@@ -10,12 +12,65 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.tables.polars_table import (
PolarsTableManagerFactory,
)
+from marimo._plugins.ui._impl.tables.table_manager import TableManager
+from tests.mocks import snapshotter
HAS_DEPS = DependencyManager.has_polars()
+snapshot = snapshotter(__file__)
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
class TestPolarsTableManagerFactory(unittest.TestCase):
+ def get_complex_data(self) -> TableManager[Any]:
+ import polars as pl
+
+ complex_data = pl.DataFrame(
+ {
+ "strings": ["a", "b", "c"],
+ "bool": [True, False, True],
+ "int": [1, 2, 3],
+ "float": [1.0, 2.0, 3.0],
+ "datetime": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ "struct": [
+ {"a": 1, "b": 2},
+ {"a": 3, "b": 4},
+ {"a": 5, "b": 6},
+ ],
+ "list": [[1, 2], [3, 4], [5, 6]],
+ "array": [[1, 2, 3], [4], []],
+ "nulls": [None, "data", None],
+ "categorical": pl.Series(["cat", "dog", "mouse"]).cast(
+ pl.Categorical
+ ),
+ # raises:
+ # pyo3_runtime.PanicException:
+ # not yet implemented: Writing Time64(Nanosecond) to JSON
+ # "time": [
+ # datetime.time(12, 30),
+ # datetime.time(13, 45),
+ # datetime.time(14, 15),
+ # ],
+ "duration": [
+ datetime.timedelta(days=1),
+ datetime.timedelta(days=2),
+ datetime.timedelta(days=3),
+ ],
+ "mixed_list": [
+ [1, "two"],
+ [3.0, False],
+ [None, datetime.datetime(2021, 1, 1)],
+ ],
+ },
+ strict=False,
+ )
+
+ return self.factory.create()(complex_data)
+
def setUp(self) -> None:
import polars as pl
@@ -46,9 +101,24 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
def test_to_csv(self) -> None:
assert isinstance(self.manager.to_csv(), bytes)
+ complex_data = self.get_complex_data()
+ data = complex_data.to_csv()
+ assert isinstance(data, bytes)
+ snapshot("polars.csv", data.decode("utf-8"))
+
def test_to_json(self) -> None:
assert isinstance(self.manager.to_json(), bytes)
+ complex_data = self.get_complex_data()
+ data = complex_data.to_json()
+ assert isinstance(data, bytes)
+ snapshot("polars.json", data.decode("utf-8"))
+
+ def test_complex_data_field_types(self) -> None:
+ complex_data = self.get_complex_data()
+ field_types = complex_data.get_field_types()
+ snapshot("polars.field_types.json", json.dumps(field_types))
+
def test_select_rows(self) -> None:
indices = [0, 2]
selected_manager = self.manager.select_rows(indices)
@@ -57,8 +127,8 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
def test_select_rows_empty(self) -> None:
selected_manager = self.manager.select_rows([])
- assert selected_manager.data.shape == (0, 0)
- assert selected_manager.data.columns == []
+ assert selected_manager.data.shape == (0, 5)
+ assert selected_manager.data.columns == ["A", "B", "C", "D", "E"]
def test_select_columns(self) -> None:
columns = ["A"]
diff --git a/tests/mocks.py b/tests/mocks.py
index 9c83e929db..49b63e9d8a 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -41,21 +41,40 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:
with open(filepath, "r") as f:
expected = normalize(f.read())
- with open(filepath, "w") as f:
- f.write(result)
-
assert result, "Result is empty"
assert expected, "Expected is empty"
- text_diff = "\n".join(
- list(
- difflib.unified_diff(
- expected.splitlines(),
- result.splitlines(),
- lineterm="",
+ def write_result() -> None:
+ with open(filepath, "w") as f:
+ f.write(result)
+
+ is_json = filename.endswith(".json")
+ if is_json:
+ import json
+
+ expected = json.loads(expected)
+ result = json.loads(result)
+
+ if expected != result:
+ write_result()
+ print("Snapshot updated")
+
+ assert expected == result
+ else:
+ text_diff = "\n".join(
+ list(
+ difflib.unified_diff(
+ expected.splitlines(),
+ result.splitlines(),
+ lineterm="",
+ )
)
)
- )
- assert result == expected, f"Snapshot differs:\n{text_diff}"
+
+ if text_diff:
+ write_result()
+ print("Snapshot updated")
+
+ assert result == expected, f"Snapshot differs:\n{text_diff}"
return snapshot