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
fixes: enable nested list & dict filtering, better display of filters (#4954)
Shahmir Varqhac35e56bc977e
diff --git a/.github/workflows/dev_build.yaml b/.github/workflows/dev_build.yamlindex f3c82f1d5f..b3831917f2 100644--- a/.github/workflows/dev_build.yaml+++ b/.github/workflows/dev_build.yaml@@ -14,7 +14,7 @@ jobs:runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4- - uses: prefix-dev/[email protected]+ - uses: prefix-dev/[email protected]with:pixi-version: v0.47.0cache: truediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex dc4aa75dab..49ef50fa50 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -384,4 +384,4 @@ marimo edit## Your first PR-Marimo has a variety of CI jobs that run on pull requests. All new PRs will fail until you have signed the [CLA](https://marimo.io/cla). Don't fret. You can sign the CLA by leaving a comment in the PR with text of `I have read the CLA Document and I hereby sign the CLA`+Marimo has a variety of CI jobs that run on pull requests. All new PRs will fail until you have signed the [CLA](https://marimo.io/cla). Don't fret. You can sign the CLA by leaving a comment in the PR with text of `I have read the CLA Document and I hereby sign the CLA`diff --git a/frontend/src/components/data-table/charts/__tests__/renderer.test.ts b/frontend/src/components/data-table/charts/__tests__/renderer.test.tsnew file mode 100644index 0000000000..d1b5ed8080--- /dev/null+++ b/frontend/src/components/data-table/charts/__tests__/renderer.test.ts@@ -0,0 +1,20 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { renderUnknownValue } from "@/components/data-table/renderers";++describe("renderUnknownValue", () => {+ it("should render an object as a JSON string", () => {+ expect(renderUnknownValue({ value: { a: 1 } })).toBe('{"a":1}');+ });++ it("should render a null value as raw string when", () => {+ expect(renderUnknownValue({ value: null })).toBe("null");+ });++ it("should render a null value as an empty string when specified", () => {+ expect(renderUnknownValue({ value: null, nullAsEmptyString: true })).toBe(+ "",+ );+ });+});diff --git a/frontend/src/components/data-table/column-header.tsx b/frontend/src/components/data-table/column-header.tsxindex 3960084b39..d6b1aaff75 100644--- a/frontend/src/components/data-table/column-header.tsx+++ b/frontend/src/components/data-table/column-header.tsx@@ -49,6 +49,7 @@ import {CommandList,} from "../ui/command";import { DraggablePopover } from "../ui/draggable-popover";+import { renderUnknownValue } from "./renderers";const TOP_K_ROWS = 30;@@ -475,10 +476,12 @@ const PopoverFilterByValues = <TData, TValue>({)}{filteredData.map(([value, count], rowIndex) => {const isSelected = chosenValues.has(value);+ const valueString = renderUnknownValue({ value });+return (<CommandItemkey={rowIndex}- value={String(value)}+ value={valueString}className="[&:not(:last-child)]:border-b rounded-none px-3"onSelect={() => handleToggle(value)}>@@ -488,7 +491,7 @@ const PopoverFilterByValues = <TData, TValue>({className="mr-3 h-3.5 w-3.5"/><span className="flex-1 overflow-hidden max-h-20 line-clamp-3">- {String(value)}+ {valueString}</span><span className="ml-3">{count}</span></CommandItem>diff --git a/frontend/src/components/data-table/filter-pills.tsx b/frontend/src/components/data-table/filter-pills.tsxindex 80ab6b91c5..c7e1c929cf 100644--- a/frontend/src/components/data-table/filter-pills.tsx+++ b/frontend/src/components/data-table/filter-pills.tsx@@ -10,6 +10,7 @@ import { Badge } from "../ui/badge";import type { ColumnFilterValue } from "./filters";import { logNever } from "@/utils/assertNever";import { XIcon } from "lucide-react";+import { renderUnknownValue } from "./renderers";interface Props<TData> {filters: ColumnFiltersState | undefined;@@ -79,7 +80,10 @@ function formatValue(value: ColumnFilterValue) {return `is ${value.value ? "True" : "False"}`;}if (value.type === "select") {- return `is in [${value.options.join(", ")}]`;+ const stringifiedOptions = value.options.map((o) =>+ renderUnknownValue({ value: o }),+ );+ return `is in [${stringifiedOptions.join(", ")}]`;}if (value.type === "text") {return `contains "${value.text}"`;diff --git a/frontend/src/components/data-table/header-items.tsx b/frontend/src/components/data-table/header-items.tsxindex 9af2dc0ebc..b6de1d4d3d 100644--- a/frontend/src/components/data-table/header-items.tsx+++ b/frontend/src/components/data-table/header-items.tsx@@ -250,7 +250,7 @@ export function renderFilterByValues<TData, TValue>(return null;}- // there is not yet good support for filtering on lists, dicts, etc.+ // there are some edge cases which do not support filtering (eg. dicts with None values)const filterType = column.columnDef.meta?.filterType;if (!filterType) {return null;diff --git a/frontend/src/components/data-table/renderers.tsx b/frontend/src/components/data-table/renderers.tsxindex de88cb5393..1580738ff0 100644--- a/frontend/src/components/data-table/renderers.tsx+++ b/frontend/src/components/data-table/renderers.tsx@@ -178,3 +178,23 @@ function columnSizingHandler<TData>([column.id]: thead.getBoundingClientRect().width,}));}++/**+ * Render an unknown value as a string. Converts objects to JSON strings.+ * @param opts.value - The value to render.+ * @param opts.nullAsEmptyString - If true, null values will be "". Else, stringify.+ */+export function renderUnknownValue(opts: {+ value: unknown;+ nullAsEmptyString?: boolean;+}): string {+ const { value, nullAsEmptyString = false } = opts;++ if (typeof value === "object" && value !== null) {+ return JSON.stringify(value);+ }+ if (value === null && nullAsEmptyString) {+ return "";+ }+ return String(value);+}diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 3c827edbd1..d4e7949d45 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -472,6 +472,7 @@ export const LoadingDataTableComponent = memo(searchQuery,useDeepCompareMemoize(props.fieldTypes),props.data,+ props.totalRows,props.lazy,paginationState.pageSize,paginationState.pageIndex,diff --git a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.pyindex c1ae7212c7..c273e00d3a 100644--- a/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py+++ b/marimo/_plugins/ui/_impl/dataframes/transforms/handlers.py@@ -128,7 +128,13 @@ class PandasTransformHandler(TransformHandler["pd.DataFrame"]):df_filter = column.str.endswith(str(value), na=False)# Handle list operations with proper Unicode handlingelif condition.operator == "in":- df_filter = df[condition.column_id].isin(value)+ # Nested lists can be filtered directly without converting the value+ if condition.value and isinstance(+ condition.value[0], (list, tuple)+ ):+ df_filter = df[condition.column_id].isin(condition.value)+ else:+ df_filter = df[condition.column_id].isin(value)else:assert_never(condition.operator)diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 799a47b17b..926bc8bdd3 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -56,6 +56,7 @@ from marimo._runtime.context.types import (get_context,)from marimo._runtime.functions import EmptyArgs, Function+from marimo._utils.hashable import is_hashablefrom marimo._utils.narwhals_utils import (can_narwhalify_lazyframe,unwrap_narwhals_dataframe,@@ -846,6 +847,15 @@ class table()@functools.lru_cache(maxsize=1) # noqa: B019+ def _apply_filters_query_sort_cached(+ self,+ filters: Optional[list[Condition]],+ query: Optional[str],+ sort: Optional[SortArgs],+ ) -> TableManager[Any]:+ """Cached version that expects hashable arguments."""+ return self._apply_filters_query_sort(filters, query, sort)+def _apply_filters_query_sort(self,filters: Optional[list[Condition]],@@ -983,9 +993,14 @@ class table(),)- # Apply filters, query, and functools.sort using the cached method- result = self._apply_filters_query_sort(- tuple(args.filters) if args.filters else None,+ # If the arguments are hashable, use the cached method+ filter_function = (+ self._apply_filters_query_sort_cached+ if is_hashable(args.filters, args.query, args.sort)+ else self._apply_filters_query_sort+ )+ result = filter_function(+ tuple(args.filters) if args.filters else None, # type: ignoreargs.query,args.sort,)diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex a693de86d7..e7b85e8ee7 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -164,24 +164,56 @@ class NarwhalsTableManager(def calculate_top_k_rows(self, column: ColumnName, k: int) -> list[tuple[Any, int]]:- frame = self.as_lazy_frame()if column not in self.get_column_names():raise ValueError(f"Column {column} not found in table.")+ frame = self.as_lazy_frame()_unique_name = "__len_count__"- result = (- frame.group_by(column)- .agg(nw.len().alias(_unique_name))- .sort([_unique_name, column], descending=[True, False])- .head(k)- .collect()- )- return [- (- unwrap_py_scalar(row[0]),- int(unwrap_py_scalar(row[1])),+ def _calculate_top_k_rows(+ df: nw.DataFrame[Any] | nw.LazyFrame[Any],+ ) -> nw.DataFrame[Any]:+ result = (+ df.group_by(column)+ .agg(nw.len().alias(_unique_name))+ .sort(+ [_unique_name, column],+ descending=[True, False],+ nulls_last=False,+ )+ .head(k))+ if isinstance(result, nw.LazyFrame):+ return result.collect()+ return result++ # For pandas, dicts and lists are unhashable, and thus cannot be grouped_by+ # so we convert them to strings+ if self.data.implementation.is_pandas():+ import pandas as pd++ df = self.data.to_native()+ if (+ isinstance(df, pd.DataFrame)+ and not df.empty+ and isinstance(df[column].iloc[0], (list, dict))+ ):+ str_data = self.data.select(self.data[column].cast(nw.String))+ result = _calculate_top_k_rows(str_data)+ str_to_val = {str(val): val for val in df[column]}++ # Map back to the original values+ return [+ (+ str_to_val.get(unwrap_py_scalar(row[0])),+ int(unwrap_py_scalar(row[1])),+ )+ for row in result.rows()+ ]++ result = _calculate_top_k_rows(frame)+ return [+ (unwrap_py_scalar(row[0]), int(unwrap_py_scalar(row[1])))for row in result.rows()]diff --git a/marimo/_utils/hashable.py b/marimo/_utils/hashable.pynew file mode 100644index 0000000000..1b04318e2e--- /dev/null+++ b/marimo/_utils/hashable.py@@ -0,0 +1,14 @@+# Copyright 2024 Marimo. All rights reserved.++from typing import Any+++def is_hashable(*values: Any) -> bool:+ """+ Check if all values passed in are hashable.+ """+ try:+ hash(values)+ return True+ except TypeError:+ return Falsediff --git a/pyproject.toml b/pyproject.tomlindex 45bdf595ef..dbe5b45c1c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -102,7 +102,7 @@ recommended = []dev = [- "click <8.1.4", # https://github.com/pallets/click/issues/2558+ "click>=8.0,<9","black~=23.12.1",# For tracing debugging"opentelemetry-api~=1.26.0",@@ -260,7 +260,7 @@ extra-dependencies = ["pyarrow>=19.0.1","pyarrow_hotfix","altair>=5.4.0",- "polars~=1.24.0",+ "polars>=1.30.0","sqlglot>=23.4","sqlalchemy>=2.0.40","pyiceberg>=0.9.0",diff --git a/tests/_plugins/ui/_impl/dataframes/test_handlers.py b/tests/_plugins/ui/_impl/dataframes/test_handlers.pyindex 523d544f2c..e064c8337e 100644--- a/tests/_plugins/ui/_impl/dataframes/test_handlers.py+++ b/tests/_plugins/ui/_impl/dataframes/test_handlers.py@@ -559,6 +559,99 @@ class TestTransformHandler:result = apply(df, transform)assert_frame_equal(result, expected)+ @staticmethod+ @pytest.mark.parametrize(+ ("df", "expected"),+ [+ (+ pl.DataFrame({"A": [[1, 2], [3, 4]]}),+ pl.DataFrame({"A": [[1, 2]]}),+ ),+ (+ pd.DataFrame({"A": [[1, 2], [3, 4]]}),+ pd.DataFrame({"A": [[1, 2]]}),+ ),+ (+ ibis.memtable({"A": [[1, 2], [3, 4]]}),+ ibis.memtable({"A": [[1, 2]]}),+ ),+ ],+ )+ def test_filter_rows_in_operator_nested_list(+ df: DataFrameType, expected: DataFrameType+ ) -> None:+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[Condition(column_id="A", operator="in", value=[[1, 2]])],+ )+ result = apply(df, transform)+ assert_frame_equal(result, expected)++ @staticmethod+ @pytest.mark.parametrize(+ ("df", "expected"),+ [+ (+ pl.DataFrame({"A": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}),+ pl.DataFrame({"A": [{"a": 1, "b": 2}]}),+ ),+ (+ pd.DataFrame({"A": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}),+ pd.DataFrame({"A": [{"a": 1, "b": 2}]}),+ ),+ pytest.param(+ ibis.memtable({"A": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}),+ ibis.memtable({"A": [{"a": 1, "b": 2}]}),+ marks=pytest.mark.xfail(+ reason="Ibis doesn't yet support dict values in filter"+ ),+ ),+ ],+ )+ def test_filter_rows_in_operator_dicts(+ df: DataFrameType, expected: DataFrameType+ ) -> None:+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[+ Condition(+ column_id="A", operator="in", value=[{"a": 1, "b": 2}]+ )+ ],+ )+ result = apply(df, transform)+ assert_frame_equal(result, expected)++ @staticmethod+ @pytest.mark.xfail(+ reason="Filtering dicts with None values is not yet supported"+ )+ @pytest.mark.parametrize(+ ("df", "expected"),+ [+ (+ pl.DataFrame({"A": [{"a": 1, "b": None}, {"a": 3, "b": 4}]}),+ pl.DataFrame({"A": [{"a": 1, "b": None}]}),+ ),+ ],+ )+ def test_filter_rows_in_operator_dicts_with_nulls(+ df: DataFrameType, expected: DataFrameType+ ) -> None:+ transform = FilterRowsTransform(+ type=TransformType.FILTER_ROWS,+ operation="keep_rows",+ where=[+ Condition(+ column_id="A", operator="in", value=[{"a": 1, "b": None}]+ )+ ],+ )+ result = apply(df, transform)+ assert_frame_equal(result, expected)+@staticmethod@pytest.mark.parametrize(("df", "expected"),diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.pyindex 3f74b5843c..2c1d3f84e9 100644--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py@@ -382,3 +382,23 @@ class TestIbisTableManagerFactory(unittest.TestCase):assert pd.isna(result[0][0])assert result[0][1] == 3assert set(result[1:]) == {(1, 1), (2, 1), (3, 1)}++ def test_calculate_top_k_rows_nested_lists(self) -> None:+ import ibis++ # Test nested lists+ table = ibis.memtable({"A": [[1, 2], [1, 2], [3, 4]]})+ manager = self.factory.create()(table)+ result = manager.calculate_top_k_rows("A", 10)+ assert result == [([1, 2], 2), ([3, 4], 1)]++ def test_calculate_top_k_rows_dicts(self) -> None:+ import ibis++ # Test dicts+ table = ibis.memtable(+ {"A": [{"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 3, "b": 4}]}+ )+ manager = self.factory.create()(table)+ result = manager.calculate_top_k_rows("A", 10)+ assert result == [({"a": 1, "b": 2}, 2), ({"a": 3, "b": 4}, 1)]diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex 73764fb40c..6c7d78056f 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -1071,34 +1071,44 @@ def test_calculate_top_k_rows(df: Any) -> None:assert normalized_result == [(3, 3), (None, 2)]+ not DependencyManager.ibis.has(),+ reason="Ibis not installed",+)+def test_calculate_top_k_rows_metadata_only_frame() -> None:+ import ibis++ df = ibis.memtable({"A": [1, 2, 3, 3, None, None]})+ manager = NarwhalsTableManager.from_dataframe(df)+ result = manager.calculate_top_k_rows("A", 10)+ assert result == [(None, 2), (3, 2), (1, 1), (2, 1)]++@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@pytest.mark.parametrize("df",create_dataframes(- {"count": [1, 2, 3, 3, None, None]},- include=SUPPORTED_LIBS,+ {"A": [[1, 2], [1, 2], [3, 4]]}, include=["polars", "pandas"]),)-def test_calculate_top_k_rows_conflicting_colname(df: Any) -> None:+def test_calculate_top_k_rows_nested_lists(df: Any) -> None:manager = NarwhalsTableManager.from_dataframe(df)-- # Test original column A- result_a = manager.calculate_top_k_rows("count", 10)- normalized_result_a = _normalize_result(result_a)- assert normalized_result_a == [(None, 2), (3, 2), (1, 1), (2, 1)]+ result = manager.calculate_top_k_rows("A", 10)+ assert result == [([1, 2], 2), ([3, 4], 1)]- reason="Narwhals doesn't support group_by for metadata-only frames"-)@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")-def test_calculate_top_k_rows_metadata_only_frame() -> None:- import ibis-- df = ibis.memtable({"A": [1, 2, 3, 3, None, None]})+ "df",+ create_dataframes(+ {"A": [{"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 3, "b": 4}]},+ include=["polars", "pandas"],+ ),+)+def test_calculate_top_k_rows_dicts(df: Any) -> None:manager = NarwhalsTableManager.from_dataframe(df)result = manager.calculate_top_k_rows("A", 10)- assert result == [(3, 2), (None, 2), (2, 1), (1, 1)]+ assert result == [({"a": 1, "b": 2}, 2), ({"a": 3, "b": 4}, 1)]def _normalize_result(result: list[tuple[Any, int]]) -> list[tuple[Any, int]]: