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.

Fix #3441 - Primitive get_sample_values (#3467)

devin-ai-integration[bot]11be99f3672a
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index c1195dc727..fefc258c23 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -288,11 +288,26 @@ class NarwhalsTableManager(
def get_unique_column_values(self, column: str) -> list[str | int | float]:
return self.data[column].unique().to_list()
- def get_sample_values(self, column: str) -> list[Any]:
+ def get_sample_values(self, column: str) -> list[str | int | float]:
# Sample 3 values from the column
SAMPLE_SIZE = 3
try:
- return self.data[column].head(SAMPLE_SIZE).to_list()
+ from enum import Enum
+
+ def to_primitive(value: Any) -> str | int | float:
+ if isinstance(value, list):
+ return str([to_primitive(v) for v in value])
+ elif isinstance(value, dict):
+ return str({k: to_primitive(v) for k, v in value.items()})
+ elif isinstance(value, Enum):
+ return value.name
+ elif isinstance(value, (float, int)):
+ return value
+ return str(value)
+
+ values = self.data[column].head(SAMPLE_SIZE).to_list()
+ # Serialize values to primitives
+ return [to_primitive(v) for v in values]
except Exception:
# May be metadata-only frame
return []
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 5cd187c213..c0ee676f49 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -673,9 +673,9 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):
"integers": lambda x: -100 if x is None else x * 2,
"floats": lambda x: "---" if x is None else f"{x:.1f}",
"booleans": lambda x: "MISSING" if x is None else str(x).upper(),
- "dates": lambda x: "No Date"
- if x is None
- else x.strftime("%Y-%m-%d"),
+ "dates": lambda x: (
+ "No Date" if x is None else x.strftime("%Y-%m-%d")
+ ),
"lists": lambda x: "Empty" if x is None else f"List({len(x)})",
}
@@ -822,6 +822,65 @@ def test_get_sample_values_with_metadata_only_frame(df: Any) -> None:
assert sample_values == []
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_get_sample_values_returns_primitives() -> None:
+ """Test that get_sample_values always returns primitive types."""
+ import polars as pl
+
+ def is_primitive(value: Any) -> bool:
+ return isinstance(
+ value,
+ (
+ str,
+ int,
+ float,
+ bool,
+ type(None),
+ datetime.datetime,
+ datetime.date,
+ ),
+ )
+
+ class Enum:
+ A = "a"
+ B = "b"
+ C = "c"
+
+ # Create a DataFrame with various types including categorical/enum-like columns
+ df = pl.DataFrame(
+ {
+ "category": pl.Series(["A", "B", "C"], dtype=pl.Categorical),
+ "mixed": pl.Series(["str", "123", "45.67"]),
+ "list": pl.Series([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
+ "dict": pl.Series(
+ [
+ {"a": 1, "b": Enum.A},
+ {"c": 3, "d": Enum.B},
+ {"e": 5, "f": Enum.C},
+ ]
+ ),
+ "enum": pl.Series([Enum.A, Enum.B, Enum.C]),
+ "dates": [
+ datetime.datetime(2021, 1, 1),
+ datetime.datetime(2021, 1, 2),
+ datetime.datetime(2021, 1, 3),
+ ],
+ },
+ )
+
+ manager: NarwhalsTableManager[Any] = NarwhalsTableManager.from_dataframe(
+ df
+ )
+
+ # Verify all values are primitives
+ for column in df.columns:
+ values = manager.get_sample_values(column)
+ for val in values:
+ assert is_primitive(val), (
+ f"Column {column} returned non-primitive or non-datetime value: {val} of type {type(val)}"
+ )
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",