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.

polars to_dicts() instead of to_json for nan handling (#7297)

Shahmir Varqhaafa7ae22f9c7
diff --git a/marimo/_messaging/msgspec_encoder.py b/marimo/_messaging/msgspec_encoder.py
index 53ca8a4708..cb8f03037e 100644
--- a/marimo/_messaging/msgspec_encoder.py
+++ b/marimo/_messaging/msgspec_encoder.py
@@ -14,7 +14,11 @@ from typing import Any
import msgspec
import msgspec.json
+from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.core.media import io_to_data_url
+
+LOGGER = _loggers.marimo_logger()
def enc_hook(obj: Any) -> Any:
@@ -126,6 +130,39 @@ def enc_hook(obj: Any) -> Any:
):
return str(obj)
+ # Handle Pillow images
+ if DependencyManager.pillow.imported():
+ try:
+ from PIL import Image
+
+ if isinstance(obj, Image.Image):
+ return io_to_data_url(obj, "image/png")
+ except Exception:
+ LOGGER.debug("Unable to convert image to data URL", exc_info=True)
+
+ # Handle Matplotlib figures
+ if DependencyManager.matplotlib.imported():
+ try:
+ import matplotlib.figure
+ from matplotlib.axes import Axes
+
+ from marimo._output.formatting import as_html
+ from marimo._plugins.stateless.flex import vstack
+
+ if isinstance(obj, matplotlib.figure.Figure):
+ html = as_html(vstack([str(obj), obj]))
+ mimetype, data = html._mime_()
+
+ if isinstance(obj, Axes):
+ html = as_html(vstack([str(obj), obj]))
+ mimetype, data = html._mime_()
+ return {"mimetype": mimetype, "data": data}
+ except Exception:
+ LOGGER.debug(
+ "Error converting matplotlib figures to HTML",
+ exc_info=True,
+ )
+
# Handle objects with __slots__
slots = getattr(obj, "__slots__", None)
if slots is not None:
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index f7fdebd003..515c9eaebb 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -13,9 +13,7 @@ from narwhals.typing import IntoDataFrameT, IntoLazyFrameT
from marimo import _loggers
from marimo._data.models import BinValue, ColumnStats, ExternalDataType
-from marimo._dependencies.dependencies import DependencyManager
from marimo._output.data.data import sanitize_json_bigint
-from marimo._plugins.core.media import io_to_data_url
from marimo._plugins.ui._impl.tables.format import (
FormatMapping,
format_value,
@@ -702,50 +700,3 @@ class NarwhalsTableManager(
if rows is None:
return f"{df_type}: {columns:,} columns"
return f"{df_type}: {rows:,} rows x {columns:,} columns"
-
- def _sanitize_table_value(self, value: Any) -> Any:
- """
- Sanitize a value for display in a table cell.
-
- Most values are unchanged, but some values are for better
- display such as Images.
- """
- if value is None:
- return None
-
- # Handle Pillow images
- if DependencyManager.pillow.imported():
- try:
- from PIL import Image
-
- if isinstance(value, Image.Image):
- return io_to_data_url(value, "image/png")
- except Exception:
- LOGGER.debug(
- "Unable to convert image to data URL", exc_info=True
- )
-
- # Handle Matplotlib figures
- if DependencyManager.matplotlib.imported():
- try:
- import matplotlib.figure
- from matplotlib.axes import Axes
-
- from marimo._output.formatting import as_html
- from marimo._plugins.stateless.flex import vstack
-
- if isinstance(value, matplotlib.figure.Figure):
- html = as_html(vstack([str(value), value]))
- mimetype, data = html._mime_()
-
- if isinstance(value, Axes):
- html = as_html(vstack([str(value), value]))
- mimetype, data = html._mime_()
- return {"mimetype": mimetype, "data": data}
- except Exception:
- LOGGER.debug(
- "Error converting matplotlib figures to HTML",
- exc_info=True,
- )
-
- return value
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 91889492a6..348fbbf19c 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -116,9 +116,6 @@ class PandasTableManagerFactory(TableManagerFactory):
if inferred_dtype == "date":
result[col] = result[col].apply(str)
- result[col] = result[col].apply(
- self._sanitize_table_value
- )
# Cast bytes to string to avoid overflow error
if self._infer_dtype(col) == "bytes":
result[col] = result[col].apply(str)
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 7fae7c7990..ad1097aa34 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -110,6 +110,11 @@ class PolarsTableManagerFactory(TableManagerFactory):
def to_json_str(
self, format_mapping: Optional[FormatMapping] = None
) -> str:
+ def to_json(result: pl.DataFrame) -> list[dict[str, Any]]:
+ # Use to_dicts instead of write_json
+ # Preserves certain types like nans, infs, -infs, etc.
+ return result.to_dicts()
+
result = self.apply_formatting(format_mapping).collect()
try:
for column in result.get_columns():
@@ -127,7 +132,7 @@ class PolarsTableManagerFactory(TableManagerFactory):
result = result.with_columns(
pl.col(column.name).cast(pl.List(pl.String))
)
- return sanitize_json_bigint(result.write_json())
+ return sanitize_json_bigint(to_json(result))
except (
BaseException
): # Sometimes, polars throws a generic exception
@@ -169,7 +174,7 @@ class PolarsTableManagerFactory(TableManagerFactory):
", ".join(f"'{col}'" for col in converted_columns),
)
- return sanitize_json_bigint(result.write_json())
+ return sanitize_json_bigint(to_json(result))
def _convert_time_to_string(
self, result: pl.DataFrame, column: pl.Series
@@ -189,7 +194,7 @@ class PolarsTableManagerFactory(TableManagerFactory):
# As of writing this, cast(pl.String) doesn't work
# for pl.Object types, so we use map_elements
column.map_elements(
- lambda v: str(self._sanitize_table_value(v)),
+ lambda v: str(v),
return_dtype=pl.String,
)
)
diff --git a/marimo/this.py b/marimo/this.py
index 32246231d6..8f9e7297f5 100644
--- a/marimo/this.py
+++ b/marimo/this.py
@@ -1,3 +1,4 @@
+# Copyright 2025 Marimo. All rights reserved.
print("""The marimo contract
To use marimo means entering into a social contract.
diff --git a/tests/_messaging/test_enc_hook.py b/tests/_messaging/test_enc_hook.py
new file mode 100644
index 0000000000..43b26d2bfb
--- /dev/null
+++ b/tests/_messaging/test_enc_hook.py
@@ -0,0 +1,65 @@
+# Copyright 2025 Marimo. All rights reserved.
+
+import json
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._messaging.msgspec_encoder import enc_hook
+
+
+def test_enc_hook() -> None:
+ """Test the enc_hook function."""
+ assert enc_hook(1) == 1
+ assert enc_hook("hello") == "hello"
+ assert enc_hook(3.14) == 3.14
+ assert enc_hook(True) is True
+ assert enc_hook(None) is None
+
+ if DependencyManager.numpy.imported():
+ import numpy as np
+
+ assert enc_hook(np.array([1, 2, 3])) == [1, 2, 3]
+ assert enc_hook(np.array([1, 2, 3])) == [1, 2, 3]
+
+
+ not DependencyManager.pillow.imported(),
+ reason="Pillow not installed",
+)
+def test_serialize_pillow_image() -> None:
+ from PIL import Image
+
+ img = Image.new("RGB", (10, 10), color="red")
+
+ result = enc_hook(img)
+
+ assert result is not None
+ assert result.startswith("data:image/png;base64,")
+
+
+ not DependencyManager.matplotlib.imported(),
+ reason="Matplotlib not installed",
+)
+def test_serialize_matplotlib_figure() -> None:
+ import matplotlib.pyplot as plt
+
+ fig, ax = plt.subplots()
+ ax.plot([1, 2, 3], [1, 2, 3])
+
+ # Serialize the figure
+ result = enc_hook(fig)
+ for obj in [fig, ax]:
+ result = enc_hook(obj)
+ assert isinstance(result, dict)
+
+ assert "mimetype" in result
+ assert "data" in result
+
+ assert "application/vnd.marimo+mimebundle" in result["mimetype"]
+ assert "image/png" in result["data"]
+
+ image_data = json.loads(result["data"])
+ assert "image/png" in image_data
+ assert image_data["image/png"].startswith("data:image/png;base64,")
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
index 4f92db9851..197de2eb7f 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.csv
@@ -1,4 +1,4 @@
-strings,bool,int,large_int,float,datetime,date,struct,list,array,nulls,category,set,imaginary,time,duration,mixed_list,enum_list
-a,true,1,18446744073709551616,1.0,2021-01-01T00:00:00.000000,2021-01-01,"{""a"":1,""b"":2}","1,2",1,,cat,"{1, 2}",(1+2j),12:30:00.000000000,1d,"1,two","A,B,C"
-b,false,2,36893488147419103233,2.0,2021-01-02T00:00:00.000000,2021-01-02,"{""a"":3,""b"":4}","3,4",2,data,dog,"{3, 4}",(3+4j),13:45:00.000000000,315µs,"3.0,0.0","A,B,C"
-c,true,3,73786976294838206466,3.0,2021-01-03T00:00:00.000000,2021-01-03,"{""a"":5,""b"":6}","5,6",3,,mouse,"{5, 6}",(5+6j),14:15:00.000000000,2h 30m,2021-01-01 00:00:00.000000,"A,B,C"
+strings,bool,int,large_int,float,datetime,date,struct,list,array,nulls,category,set,imaginary,time,duration,nans,infs,mixed_list,enum_list
+a,true,1,18446744073709551616,1.0,2021-01-01T00:00:00.000000,2021-01-01,"{""a"":1,""b"":2}","1,2",1,,cat,"{1, 2}",(1+2j),12:30:00.000000000,1d,NaN,inf,"1,two","A,B,C"
+b,false,2,36893488147419103233,2.0,2021-01-02T00:00:00.000000,2021-01-02,"{""a"":3,""b"":4}","3,4",2,data,dog,"{3, 4}",(3+4j),13:45:00.000000000,315µs,NaN,-inf,"3.0,0.0","A,B,C"
+c,true,3,73786976294838206466,3.0,2021-01-03T00:00:00.000000,2021-01-03,"{""a"":5,""b"":6}","5,6",3,,mouse,"{5, 6}",(5+6j),14:15:00.000000000,2h 30m,NaN,inf,2021-01-01 00:00:00.000000,"A,B,C"
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
index 4030284d25..80400d29d6 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json
@@ -1 +1,177 @@
-[["strings", ["string", "str"]], ["bool", ["boolean", "bool"]], ["int", ["integer", "i64"]], ["large_int", ["integer", "i128"]], ["float", ["number", "f64"]], ["datetime", ["datetime", "datetime[\u03bcs]"]], ["date", ["date", "date"]], ["struct", ["unknown", "struct[2]"]], ["list", ["unknown", "list[i64]"]], ["nested_lists", ["unknown", "list[list[i64]]"]], ["nested_arrays", ["unknown", "array[i64, (1, 2)]"]], ["array", ["unknown", "array[i64, 1]"]], ["nulls", ["string", "str"]], ["category", ["string", "cat"]], ["set", ["unknown", "object"]], ["imaginary", ["unknown", "object"]], ["time", ["time", "time"]], ["duration", ["number", "duration[\u03bcs]"]], ["mixed_list", ["unknown", "list[str]"]], ["structs_with_list", ["unknown", "struct[2]"]], ["list_with_structs", ["unknown", "list[struct[2]]"]], ["enum_list", ["unknown", "list[enum]"]], ["binary", ["unknown", "binary"]]]
\ No newline at end of file
+[
+ [
+ "strings",
+ [
+ "string",
+ "str"
+ ]
+ ],
+ [
+ "bool",
+ [
+ "boolean",
+ "bool"
+ ]
+ ],
+ [
+ "int",
+ [
+ "integer",
+ "i64"
+ ]
+ ],
+ [
+ "large_int",
+ [
+ "integer",
+ "i128"
+ ]
+ ],
+ [
+ "float",
+ [
+ "number",
+ "f64"
+ ]
+ ],
+ [
+ "datetime",
+ [
+ "datetime",
+ "datetime[\u03bcs]"
+ ]
+ ],
+ [
+ "date",
+ [
+ "date",
+ "date"
+ ]
+ ],
+ [
+ "struct",
+ [
+ "unknown",
+ "struct[2]"
+ ]
+ ],
+ [
+ "list",
+ [
+ "unknown",
+ "list[i64]"
+ ]
+ ],
+ [
+ "nested_lists",
+ [
+ "unknown",
+ "list[list[i64]]"
+ ]
+ ],
+ [
+ "nested_arrays",
+ [
+ "unknown",
+ "array[i64, (1, 2)]"
+ ]
+ ],
+ [
+ "array",
+ [
+ "unknown",
+ "array[i64, 1]"
+ ]
+ ],
+ [
+ "nulls",
+ [
+ "string",
+ "str"
+ ]
+ ],
+ [
+ "category",
+ [
+ "string",
+ "cat"
+ ]
+ ],
+ [
+ "set",
+ [
+ "unknown",
+ "object"
+ ]
+ ],
+ [
+ "imaginary",
+ [
+ "unknown",
+ "object"
+ ]
+ ],
+ [
+ "time",
+ [
+ "time",
+ "time"
+ ]
+ ],
+ [
+ "duration",
+ [
+ "number",
+ "duration[\u03bcs]"
+ ]
+ ],
+ [
+ "nans",
+ [
+ "number",
+ "f64"
+ ]
+ ],
+ [
+ "infs",
+ [
+ "number",
+ "f64"
+ ]
+ ],
+ [
+ "mixed_list",
+ [
+ "unknown",
+ "list[str]"
+ ]
+ ],
+ [
+ "structs_with_list",
+ [
+ "unknown",
+ "struct[2]"
+ ]
+ ],
+ [
+ "list_with_structs",
+ [
+ "unknown",
+ "list[struct[2]]"
+ ]
+ ],
+ [
+ "enum_list",
+ [
+ "unknown",
+ "list[enum]"
+ ]
+ ],
+ [
+ "binary",
+ [
+ "unknown",
+ "binary"
+ ]
+ ]
+]
\ No newline at end of file
diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
index 3c3d3dc343..a877834dbf 100644
--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.json
+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.json
@@ -1 +1,202 @@
-[{"strings":"a","bool":true,"int":1,"large_int":"18446744073709551616","float":1.0,"datetime":"2021-01-01 00:00:00","date":"2021-01-01","struct":{"a":1,"b":2},"list":[1,2],"nested_lists":[[1,2]],"nested_arrays":[[1,2]],"array":[1],"nulls":null,"category":"cat","set":"{1, 2}","imaginary":"(1+2j)","time":"12:30:00","duration":"1d","mixed_list":["1","two"],"structs_with_list":{"a":[1,2],"b":2},"list_with_structs":[{"a":1,"c":null},{"a":null,"c":3}],"enum_list":["A","B","C"],"binary":"b'\\x00\\x00\\x00\\x00\\x01\\xc0U\\xe8\\xb1n1\\xc0T@D\\xf1?Bc\\x95\\x83'"},{"strings":"b","bool":false,"int":2,"large_int":"36893488147419103233","float":2.0,"datetime":"2021-01-02 00:00:00","date":"2021-01-02","struct":{"a":3,"b":4},"list":[3,4],"nested_lists":[[3,4]],"nested_arrays":[[3,4]],"array":[2],"nulls":"data","category":"dog","set":"{3, 4}","imaginary":"(3+4j)","time":"13:45:00","duration":"315\u00b5s","mixed_list":["3.0","0.0"],"structs_with_list":{"a":[3,4],"b":4},"list_with_structs":[{"a":null,"c":null}],"enum_list":["A","B","C"],"binary":"b'world'"},{"strings":"c","bool":true,"int":3,"large_int":"73786976294838206466","float":3.0,"datetime":"2021-01-03 00:00:00","date":"2021-01-03","struct":{"a":5,"b":6},"list":[5,6],"nested_lists":[[5,6]],"nested_arrays":[[5,6]],"array":[3],"nulls":null,"category":"mouse","set":"{5, 6}","imaginary":"(5+6j)","time":"14:15:00","duration":"2h 30m","mixed_list":[null,"2021-01-01 00:00:00.000000"],"structs_with_list":{"a":null,"b":null},"list_with_structs":[],"enum_list":["A","B","C"],"binary":"b'foo'"}]
\ No newline at end of file
+[
+ {
+ "strings": "a",
+ "bool": true,
+ "int": 1,
+ "large_int": {
+ "$bigint": "18446744073709551616"
+ },
+ "float": 1.0,
+ "datetime": "2021-01-01 00:00:00",
+ "date": "2021-01-01",
+ "struct": {
+ "a": 1,
+ "b": 2
+ },
+ "list": [
+ 1,
+ 2
+ ],
+ "nested_lists": [
+ [
+ 1,
+ 2
+ ]
+ ],
+ "nested_arrays": [
+ [
+ 1,
+ 2
+ ]
+ ],
+ "array": [
+ 1
+ ],
+ "nulls": null,
+ "category": "cat",
+ "set": [
+ 1,
+ 2
+ ],
+ "imaginary": "(1+2j)",
+ "time": "12:30:00",
+ "duration": "1d",
+ "nans":NaN,
+ "infs": "inf",
+ "mixed_list": [
+ "1",
+ "two"
+ ],
+ "structs_with_list": {
+ "a": [
+ 1,
+ 2
+ ],
+ "b": 2
+ },
+ "list_with_structs": [
+ {
+ "a": 1,
+ "c": null
+ },
+ {
+ "a": null,
+ "c": 3
+ }
+ ],
+ "enum_list": [
+ "A",
+ "B",
+ "C"
+ ],
+ "binary": "\u0000\u0000\u0000\u0000\u0001\u00c0U\u00e8\u00b1n1\u00c0T@D\u00f1?Bc\u0095\u0083"
+ },
+ {
+ "strings": "b",
+ "bool": false,
+ "int": 2,
+ "large_int": {
+ "$bigint": "36893488147419103233"
+ },
+ "float": 2.0,
+ "datetime": "2021-01-02 00:00:00",
+ "date": "2021-01-02",
+ "struct": {
+ "a": 3,
+ "b": 4
+ },
+ "list": [
+ 3,
+ 4
+ ],
+ "nested_lists": [
+ [
+ 3,
+ 4
+ ]
+ ],
+ "nested_arrays": [
+ [
+ 3,
+ 4
+ ]
+ ],
+ "array": [
+ 2
+ ],
+ "nulls": "data",
+ "category": "dog",
+ "set": [
+ 3,
+ 4
+ ],
+ "imaginary": "(3+4j)",
+ "time": "13:45:00",
+ "duration": "315\u00b5s",
+ "nans":NaN,
+ "infs": "-inf",
+ "mixed_list": [
+ "3.0",
+ "0.0"
+ ],
+ "structs_with_list": {
+ "a": [
+ 3,
+ 4
+ ],
+ "b": 4
+ },
+ "list_with_structs": [
+ {
+ "a": null,
+ "c": null
+ }
+ ],
+ "enum_list": [
+ "A",
+ "B",
+ "C"
+ ],
+ "binary": "world"
+ },
+ {
+ "strings": "c",
+ "bool": true,
+ "int": 3,
+ "large_int": {
+ "$bigint": "73786976294838206466"
+ },
+ "float": 3.0,
+ "datetime": "2021-01-03 00:00:00",
+ "date": "2021-01-03",
+ "struct": {
+ "a": 5,
+ "b": 6
+ },
+ "list": [
+ 5,
+ 6
+ ],
+ "nested_lists": [
+ [
+ 5,
+ 6
+ ]
+ ],
+ "nested_arrays": [
+ [
+ 5,
+ 6
+ ]
+ ],
+ "array": [
+ 3
+ ],
+ "nulls": null,
+ "category": "mouse",
+ "set": [
+ 5,
+ 6
+ ],
+ "imaginary": "(5+6j)",
+ "time": "14:15:00",
+ "duration": "2h 30m",
+ "nans":NaN,
+ "infs": "inf",
+ "mixed_list": [
+ null,
+ "2021-01-01 00:00:00.000000"
+ ],
+ "structs_with_list": {
+ "a": null,
+ "b": null
+ },
+ "list_with_structs": [],
+ "enum_list": [
+ "A",
+ "B",
+ "C"
+ ],
+ "binary": "foo"
+ }
+]
\ No newline at end of file
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index cc5689a834..47bf6168a1 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -1603,120 +1603,6 @@ def test_calculate_top_k_rows_cache_invalidation(df: Any) -> None:
assert result1 != result2
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
-class TestSanitizeTableValue:
- """Tests for the _sanitize_table_value method."""
-
- def setUp(self) -> None:
- import polars as pl
-
- self.data = pl.DataFrame({"A": [1, 2, 3]})
- self.manager = NarwhalsTableManager.from_dataframe(self.data)
-
- def test_sanitize_none(self) -> None:
- """Test that None values are returned as-is."""
- manager = self._get_manager()
- assert manager._sanitize_table_value(None) is None
-
- def test_sanitize_primitive_values(self) -> None:
- """Test that primitive values are returned unchanged."""
- manager = self._get_manager()
- assert manager._sanitize_table_value(42) == 42
- assert manager._sanitize_table_value("hello") == "hello"
- assert manager._sanitize_table_value(3.14) == 3.14
- assert manager._sanitize_table_value(True) is True
-
- @pytest.mark.skipif(
- not DependencyManager.pillow.has(),
- reason="Pillow not installed",
- )
- def test_sanitize_pillow_image(self) -> None:
- """Test that Pillow images are converted to data URLs."""
- from PIL import Image
-
- manager = self._get_manager()
-
- # Create a simple test image
- img = Image.new("RGB", (10, 10), color="red")
-
- result = manager._sanitize_table_value(img)
-
- # Verify it returns a data URL string
- assert isinstance(result, str)
- assert result.startswith("data:image/png;base64,")
-
- @pytest.mark.skipif(
- not DependencyManager.matplotlib.has(),
- reason="Matplotlib not installed",
- )
- def test_sanitize_matplotlib_figure(self) -> None:
- """Test that Matplotlib figures are returned unchanged (no conversion)."""
- import matplotlib.pyplot as plt
-
- manager = self._get_manager()
-
- # Create a simple figure
- fig, ax = plt.subplots()
- ax.plot([1, 2, 3], [1, 2, 3])
-
- result = manager._sanitize_table_value(fig)
-
- # Figure is currently returned unchanged because there's no return statement for figures
- # (only for axes)
- assert result == fig
-
- plt.close(fig)
-
- @pytest.mark.skipif(
- not DependencyManager.matplotlib.has(),
- reason="Matplotlib not installed",
- )
- def test_sanitize_matplotlib_axes(self) -> None:
- """Test that Matplotlib axes are converted to HTML."""
- import matplotlib.pyplot as plt
-
- manager = self._get_manager()
-
- # Create a simple axes
- fig, ax = plt.subplots()
- ax.plot([1, 2, 3], [1, 2, 3])
-
- result = manager._sanitize_table_value(ax)
-
- # Verify it returns a dict with mimetype and data
- assert isinstance(result, dict)
- assert "mimetype" in result
- assert "data" in result
-
- plt.close(fig)
-
- def test_sanitize_unsupported_types(self) -> None:
- """Test that unsupported types are returned unchanged."""
- manager = self._get_manager()
-
- # Test various unsupported types
- class CustomClass:
- pass
-
- obj = CustomClass()
- assert manager._sanitize_table_value(obj) == obj
-
- # Test dict
- d = {"key": "value"}
- assert manager._sanitize_table_value(d) == d
-
- # Test list
- lst = [1, 2, 3]
- assert manager._sanitize_table_value(lst) == lst
-
- def _get_manager(self) -> NarwhalsTableManager[Any]:
- """Helper method to create a manager."""
- import polars as pl
-
- data = pl.DataFrame({"A": [1, 2, 3]})
- return NarwhalsTableManager.from_dataframe(data)
-
-
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
class TestRichElements:
"""Tests for rich elements."""
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index 0e1862b74d..d1377ed507 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import datetime
import json
+import math
import unittest
from enum import Enum
from math import isnan
@@ -95,6 +96,8 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
datetime.timedelta(microseconds=315),
datetime.timedelta(hours=2, minutes=30),
],
+ "nans": [float("nan"), -float("nan"), float("nan") + 1],
+ "infs": [float("inf"), -float("inf"), float("inf") + 1],
"mixed_list": [
[1, "two"],
[3.0, False],
@@ -228,6 +231,14 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
assert json_data[1]["duration"] == "315µs"
assert json_data[2]["duration"] == "2h 30m"
+ # Check nans and infs
+ assert math.isnan(json_data[0]["nans"])
+ assert math.isnan(json_data[1]["nans"])
+ assert math.isnan(json_data[2]["nans"])
+ assert json_data[0]["infs"] == "inf"
+ assert json_data[1]["infs"] == "-inf"
+ assert json_data[2]["infs"] == "inf"
+
def test_complex_data_field_types(self) -> None:
complex_data = self.get_complex_data()
field_types = complex_data.get_field_types()