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
feat: add initial selection table (#3509)
Shahmir Varqha4a20eaf904c5
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex d62837ff92..e04287e3b1 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -99,7 +99,11 @@ class SortArgs:@mddoc-class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):+class table(+ UIElement[+ Union[List[str], List[int]], Union[List[JSONType], IntoDataFrame]+ ]+):"""A table component with selectable rows.Get the selected rows with `table.value`. The table data can be supplied as:@@ -189,6 +193,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):Defaults to True when above 10 rows, False otherwise.selection (Literal["single", "multi"], optional): 'single' or 'multi' to enable row selection,or None to disable. Defaults to "multi".+ initial_selection (List[int], optional): Indices of the rows you want selected by default.page_size (int, optional): The number of rows to show per page. Defaults to 10.show_column_summaries (Union[bool, Literal["stats", "chart"]], optional): Whether to show column summaries.Defaults to True when the table has less than 40 columns, False otherwise.@@ -221,6 +226,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):],pagination: Optional[bool] = None,selection: Optional[Literal["single", "multi"]] = "multi",+ initial_selection: Optional[List[int]] = None,page_size: int = 10,show_column_summaries: Optional[Union[bool, Literal["stats", "chart"]]@@ -294,6 +300,23 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):# Holds the data after user selecting from the componentself._selected_manager: Optional[TableManager[Any]] = None+ initial_value = []+ if initial_selection and self._manager.supports_selection():+ if selection == "single" and len(initial_selection) > 1:+ raise ValueError(+ "For single selection mode, initial_selection can only contain one row index"+ )+ try:+ self._selected_manager = self._searched_manager.select_rows(+ initial_selection+ )+ except IndexError as e:+ raise IndexError(+ "initial_selection contains invalid row indices"+ ) from e+ initial_value = initial_selection+ self._has_any_selection = True+# We will need this when calling table manager's to_data()self._format_mapping = format_mapping@@ -382,7 +405,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):super().__init__(component_name=table._name,label=label,- initial_value=[],+ initial_value=initial_value,args={"data": search_result.data,"total-rows": total_rows,@@ -445,7 +468,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):return ""def _convert_value(- self, value: list[str]+ self, value: Union[List[int] | List[str]]) -> Union[List[JSONType], "IntoDataFrame"]:indices = [int(v) for v in value]self._selected_manager = self._searched_manager.select_rows(indices)diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex ae56430497..a446bcf95f 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -223,6 +223,25 @@ def test_value_with_selection() -> None:assert list(table._convert_value(["0", "2"])) == ["banana", "cherry"]+def test_value_with_initial_selection() -> None:+ data = ["banana", "apple", "cherry", "date", "elderberry"]+ table = ui.table(data, initial_selection=[0, 2])+ assert table.value == ["banana", "cherry"]+++def test_invalid_initial_selection() -> None:+ data = ["banana", "apple"]+ with pytest.raises(IndexError):+ ui.table(data, initial_selection=[2])++ with pytest.raises(TypeError):+ ui.table(data, initial_selection=["apple"])++ # multiple rows cannot be selected for single selection mode+ with pytest.raises(ValueError):+ ui.table(data, selection="single", initial_selection=[0, 1])++def test_value_with_sorting_then_selection() -> None:data = ["banana", "apple", "cherry", "date", "elderberry"]table = ui.table(data)