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
improvement: clamp tables at 50 columnns by default (#3000)
Myles Scolnick6b08d29ee513
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsxindex c684e63b3a..28f81f5017 100644--- a/frontend/src/components/data-table/TableActions.tsx+++ b/frontend/src/components/data-table/TableActions.tsx@@ -15,6 +15,7 @@ interface TableActionsProps<TData> {isSearchEnabled: boolean;setIsSearchEnabled: React.Dispatch<React.SetStateAction<boolean>>;pagination: boolean;+ totalColumns: number;selection?: "single" | "multi" | null;onRowSelectionChange?: (value: RowSelectionState) => void;table: Table<TData>;@@ -27,6 +28,7 @@ export const TableActions = <TData,>({isSearchEnabled,setIsSearchEnabled,pagination,+ totalColumns,selection,onRowSelectionChange,table,@@ -48,6 +50,7 @@ export const TableActions = <TData,>({)}{pagination ? (<DataTablePagination+ totalColumns={totalColumns}selection={selection}onSelectAllRowsChange={onRowSelectionChangediff --git a/frontend/src/components/data-table/column-summary.tsx b/frontend/src/components/data-table/column-summary.tsxindex 1aa11daaf6..4aec7fed0a 100644--- a/frontend/src/components/data-table/column-summary.tsx+++ b/frontend/src/components/data-table/column-summary.tsx@@ -32,6 +32,8 @@ export const TableColumnSummary = <TData, TValue>({chart = (<DelayMountmilliseconds={200}+ visibility={true}+ rootMargin="200px"fallback={<ChartSkeleton seed={columnId} width={130} height={60} />}><LazyVegaLitediff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 1be64114cf..398990657a 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -41,6 +41,7 @@ interface DataTableProps<TData> extends Partial<DownloadActionProps> {setSorting?: OnChangeFn<SortingState>; // controlled sorting// PaginationtotalRows: number | "too_many";+ totalColumns: number;pagination?: boolean;manualPagination?: boolean; // server-side paginationpaginationState?: PaginationState; // controlled pagination@@ -68,6 +69,7 @@ const DataTableInternal = <TData,>({columns,data,selection,+ totalColumns,totalRows,manualSorting = false,sorting,@@ -168,6 +170,7 @@ const DataTableInternal = <TData,>({</div><TableActionsenableSearch={enableSearch}+ totalColumns={totalColumns}onSearchQueryChange={onSearchQueryChange}isSearchEnabled={isSearchEnabled}setIsSearchEnabled={setIsSearchEnabled}diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsxindex bd25b90edb..2db23a2492 100644--- a/frontend/src/components/data-table/pagination.tsx+++ b/frontend/src/components/data-table/pagination.tsx@@ -16,6 +16,7 @@ import { range } from "lodash-es";interface DataTablePaginationProps<TData> {table: Table<TData>;selection?: "single" | "multi" | null;+ totalColumns: number;onSelectAllRowsChange?: (value: boolean) => void;}@@ -23,6 +24,7 @@ export const DataTablePagination = <TData,>({table,selection,onSelectAllRowsChange,+ totalColumns,}: DataTablePaginationProps<TData>) => {const renderTotal = () => {const selected = Object.keys(table.getState().rowSelection).length;@@ -76,13 +78,8 @@ export const DataTablePagination = <TData,>({);}- let numColumns = table.getAllColumns().length;- // If we have a selection column, subtract one from the total columns- if (selection != null) {- numColumns -= 1;- }const rowsLabel = `${prettyNumber(numRows)} ${new PluralWord("row").pluralize(numRows)}`;- const columnsLabel = `${prettyNumber(numColumns)} ${new PluralWord("column").pluralize(numColumns)}`;+ const columnsLabel = `${prettyNumber(totalColumns)} ${new PluralWord("column").pluralize(totalColumns)}`;return <span>{[rowsLabel, columnsLabel].join(", ")}</span>;};diff --git a/frontend/src/components/editor/file-tree/renderers.tsx b/frontend/src/components/editor/file-tree/renderers.tsxindex e74ad2a6cc..c3e023bce1 100644--- a/frontend/src/components/editor/file-tree/renderers.tsx+++ b/frontend/src/components/editor/file-tree/renderers.tsx@@ -36,6 +36,7 @@ export const CsvViewer: React.FC<{ contents: string }> = ({ contents }) => {data={data}totalRows={data.length}columns={columns}+ totalColumns={columns.length}manualPagination={false}paginationState={pagination}setPaginationState={setPagination}diff --git a/frontend/src/components/utils/delay-mount.tsx b/frontend/src/components/utils/delay-mount.tsxindex 76fba8ef9e..9f0a71d306 100644--- a/frontend/src/components/utils/delay-mount.tsx+++ b/frontend/src/components/utils/delay-mount.tsx@@ -1,16 +1,66 @@/* Copyright 2024 Marimo. All rights reserved. */-import React from "react";+import { useIntersectionObserver } from "@uidotdev/usehooks";+import React, { useEffect, useState } from "react";interface Props {+ /**+ * The delay in milliseconds before mounting the children.+ */milliseconds: number;++ /**+ * The content to be rendered after the delay.+ */children: React.ReactNode;++ /**+ * The content to be rendered while waiting for the delay or visibility condition.+ */fallback?: React.ReactNode;++ /**+ * If true, the children will only be rendered if the component has been visible in the viewport at least once.+ */+ visibility?: boolean;++ /**+ * The threshold at which the visibility is considered. A number between 0 and 1.+ */+ threshold?: number;++ /**+ * The root margin for the intersection observer.+ */+ rootMargin?: string;}-export const DelayMount = ({ milliseconds, children, fallback }: Props) => {- const [mounted, setMounted] = React.useState(false);+/**+ * DelayMount component delays the rendering of its children until a specified time has passed.+ * It can also conditionally render based on the visibility of the component in the viewport.+ */+export const DelayMount = ({+ milliseconds,+ children,+ fallback,+ visibility = false,+ threshold = 0,+ rootMargin = "0px",+}: Props) => {+ const [mounted, setMounted] = useState(false);+ const [hasBeenVisible, setHasBeenVisible] = useState(false);+ const [ref, entry] = useIntersectionObserver({+ threshold,+ root: null,+ rootMargin,+ });++ useEffect(() => {+ if (entry?.isIntersecting) {+ setHasBeenVisible(true);+ }+ }, [entry?.isIntersecting]);- React.useEffect(() => {+ useEffect(() => {const timeout = setTimeout(() => {setMounted(true);}, milliseconds);@@ -20,5 +70,12 @@ export const DelayMount = ({ milliseconds, children, fallback }: Props) => {};}, [milliseconds]);- return mounted ? children : fallback;+ // Determine if the children should be shown+ // If visibility is true, only show the children if the component has been visible in the viewport at least once.+ // If visibility is false, always show the children after the delay.+ const shouldShow = visibility && !hasBeenVisible ? false : mounted;++ return (+ <div ref={visibility ? ref : null}>{shouldShow ? children : fallback}</div>+ );};diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsxindex e2fbb1decb..7a4db2d0b0 100644--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx@@ -48,7 +48,12 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor")pagination: z.boolean().default(false),pageSize: z.number().default(10),fieldTypes: z- .array(z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]))+ .array(+ z.tuple([+ z.coerce.string(),+ z.tuple([z.enum(DATA_TYPES), z.string()]),+ ]),+ ).nullish(),}),)diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex 0612bbfc39..d5ebaf2d35 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -75,6 +75,7 @@ interface Data<T> {freezeColumnsRight?: string[];textJustifyColumns?: Record<string, "left" | "center" | "right">;wrappedColumns?: string[];+ totalColumns: number;}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions@@ -119,8 +120,14 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").optional(),wrappedColumns: z.array(z.string()).optional(),fieldTypes: z- .array(z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]))+ .array(+ z.tuple([+ z.coerce.string(),+ z.tuple([z.enum(DATA_TYPES), z.string()]),+ ]),+ ).nullish(),+ totalColumns: z.number(),}),).withFunctions<Functions>({@@ -440,6 +447,7 @@ const DataTableComponent = ({freezeColumnsRight,textJustifyColumns,wrappedColumns,+ totalColumns,}: DataTableProps<unknown> &DataTableSearchProps & {data: unknown[];@@ -464,6 +472,7 @@ const DataTableComponent = ({}, [fieldTypes, columnSummaries]);const fieldTypesOrInferred = fieldTypes ?? inferFieldTypes(data);+ const shownColumns = fieldTypesOrInferred.length;const columns = useMemo(() =>@@ -515,6 +524,11 @@ const DataTableComponent = ({Result clipped. If no LIMIT is given, we only show the first 300 rows.</Banner>)}+ {shownColumns < totalColumns && (+ <Banner className="mb-2 rounded">+ Result clipped. Showing {shownColumns} of {totalColumns} columns.+ </Banner>+ )}{columnSummaries?.is_disabled && (// Note: Keep the text in sync with the constant defined in table_manager.py// This hard-code can be removed when Functions can pass structural@@ -532,6 +546,7 @@ const DataTableComponent = ({className={className}sorting={sorting}totalRows={totalRows}+ totalColumns={totalColumns}manualSorting={true}setSorting={setSorting}pagination={pagination}diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex d33e057828..5a6f3bb5ce 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -263,6 +263,7 @@ export const DataFrameComponent = memo(className="rounded-b border-x border-b"data={url || ""}totalRows={total_rows ?? 0}+ totalColumns={Object.keys(columns).length}pageSize={pageSize}pagination={true}fieldTypes={field_types}diff --git a/frontend/src/stories/data-table.stories.tsx b/frontend/src/stories/data-table.stories.tsxindex 03a2cc8f15..2035ab3872 100644--- a/frontend/src/stories/data-table.stories.tsx+++ b/frontend/src/stories/data-table.stories.tsx@@ -15,6 +15,7 @@ export const Default = {render: () => (<DataTabletotalRows={100}+ totalColumns={2}paginationState={{ pageIndex: 0, pageSize: 10 }}setPaginationState={Functions.NOOP}data={[@@ -51,6 +52,7 @@ export const Empty1 = {render: () => (<DataTabletotalRows={100}+ totalColumns={2}paginationState={{ pageIndex: 0, pageSize: 10 }}setPaginationState={Functions.NOOP}data={[]}@@ -78,6 +80,7 @@ export const Empty2 = {render: () => (<DataTabletotalRows={100}+ totalColumns={2}paginationState={{ pageIndex: 0, pageSize: 10 }}setPaginationState={Functions.NOOP}data={[]}@@ -91,6 +94,7 @@ export const Pagination = {render: () => (<DataTabletotalRows={100}+ totalColumns={2}paginationState={{ pageIndex: 0, pageSize: 10 }}setPaginationState={Functions.NOOP}data={[diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 7e90ee545b..dd3f26032e 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -205,6 +205,8 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):- `wrapped_columns`: list of column names to wrap- `label`: markdown label for the element- `on_change`: optional callback to run when this element's value changes+ - `max_columns`: maximum number of columns to display, defaults to 50.+ Set to None to show all columns."""_name: Final[str] = "marimo-table"@@ -220,6 +222,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):pagination: Optional[bool] = None,selection: Optional[Literal["single", "multi"]] = "multi",page_size: int = 10,+ max_columns: Optional[int] = 50,show_column_summaries: Optional[bool] = None,format_mapping: Optional[Dict[str, Union[str, Callable[..., Any]]]@@ -255,6 +258,7 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):self._data = data# Holds the original dataself._manager = get_table_manager(data)+ self._max_columns = max_columns# Set the default value for show_column_summaries,# if it is not set by the user@@ -363,6 +367,13 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):if column not in column_names:raise ValueError(f"Column '{column}' not found in table.")+ # Clamp field types to max columns+ if (+ self._max_columns is not None+ and len(field_types) > self._max_columns+ ):+ field_types = field_types[: self._max_columns]+super().__init__(component_name=table._name,label=label,@@ -370,6 +381,8 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):args={"data": search_result.data,"total-rows": total_rows,+ "total-columns": self._manager.get_num_columns(),+ "banner-text": self._get_banner_text(),"pagination": pagination,"page-size": page_size,"field-types": field_types or None,@@ -412,6 +425,14 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):) -> TableData:return self._data+ def _get_banner_text(self) -> str:+ total_columns = self._manager.get_num_columns()+ if self._max_columns is not None and total_columns > self._max_columns:+ return (+ f"Only showing {self._max_columns} of {total_columns} columns."+ )+ return ""+def _convert_value(self, value: list[str]) -> Union[List[JSONType], "IntoDataFrame"]:@@ -531,15 +552,23 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):def search(self, args: SearchTableArgs) -> SearchTableResponse:offset = args.page_number * args.page_size+ def clamp_rows_and_columns(manager: TableManager[Any]) -> JSONType:+ # Limit to page and column clamping for the frontend+ data = manager.take(args.page_size, offset)+ column_names = data.get_column_names()+ if (+ self._max_columns is not None+ and len(column_names) > self._max_columns+ ):+ data = data.select_columns(column_names[: self._max_columns])+ return data.to_data(self._format_mapping)+# If no query or sort, return nothing# The frontend will just show the original dataif not args.query and not args.sort and not args.filters:self._searched_manager = self._manager- data = self._manager.take(args.page_size, offset).to_data(- self._format_mapping- )return SearchTableResponse(- data=data,+ data=clamp_rows_and_columns(self._manager),total_rows=self._manager.get_num_rows(force=True) or 0,)@@ -552,11 +581,9 @@ class table(UIElement[List[str], Union[List[JSONType], IntoDataFrame]]):# Save the manager to be used for selectionself._searched_manager = result- data = result.take(args.page_size, offset).to_data(- self._format_mapping- )+return SearchTableResponse(- data=data,+ data=clamp_rows_and_columns(result),total_rows=result.get_num_rows(force=True) or 0,)diff --git a/marimo/_smoke_tests/issues/2991-df-columns.py b/marimo/_smoke_tests/issues/2991-df-columns.pynew file mode 100644index 0000000000..45c9d33742--- /dev/null+++ b/marimo/_smoke_tests/issues/2991-df-columns.py@@ -0,0 +1,94 @@++# /// script+# requires-python = ">=3.10"+# dependencies = [+# "marimo",+# "numpy==2.1.3",+# "pandas==2.2.3",+# ]+# ///++import marimo++__generated_with = "0.9.27"+app = marimo.App(width="medium")+++def __():+ import pandas as pd+ import marimo as mo+ import numpy as np+ return mo, np, pd+++def __(mo):+ mo.md(r"""## Lots of columns""")+ return++[email protected](hide_code=True)+def __(mo):+ mo.md("""Set cols to 10000 to crash the frontend. Number of rows appears to have no effect.""")+ return+++def __(mo):+ rows = mo.ui.number(start=1, value=10, label="rows")+ columns = mo.ui.number(start=1, value=50, label="cols")++ mo.hstack([rows, columns], justify="start")+ return columns, rows+++def __(columns, np, rows):+ data = np.zeros((rows.value, columns.value))+ return (data,)+++def __(data, pd):+ df = pd.DataFrame(data, columns=[str(i) for i in range(1, data.shape[1] + 1)])+ return (df,)+++def __(df):+ df+ return+++def __(mo):+ mo.md(+ r"""+ ## 20k rows, 40 columns++ This is the default max to show column summaries+ """+ )+ return+++def __(np, pd):+ _data = np.random.rand(20000, 40)+ column_names = [f"col{i}" for i in range(40)]+ large_df = pd.DataFrame(+ {col: _data[:, i] for i, col in enumerate(column_names)}+ )+ large_df+ return column_names, large_df+++def __():+ # mo.ui.table(df, max_columns=None)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex d6f1727d68..e8db85f3a7 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -698,3 +698,155 @@ def test_pagination_behavior() -> None:assert table._component_args["pagination"] is Trueassert table._component_args["page-size"] == 5assert len(table._component_args["data"]) == 5+++def test_column_clamping():+ # Create data with many columns+ data = {f"col{i}": [1, 2, 3] for i in range(100)}++ # Test default max_columns+ table = ui.table(data)+ assert len(table._manager.get_column_names()) == 100+ assert table._component_args["total-columns"] == 100+ assert len(table._component_args["data"][0].keys()) == 50+ assert table._component_args["field-types"] is None++ # Test custom max_columns+ table = ui.table(data, max_columns=20)+ assert len(table._manager.get_column_names()) == 100+ assert table._component_args["total-columns"] == 100+ assert len(table._component_args["data"][0].keys()) == 20+ assert table._component_args["field-types"] is None++ # Test no clamping+ table = ui.table(data, max_columns=None)+ assert len(table._manager.get_column_names()) == 100+ assert table._component_args["total-columns"] == 100+ assert len(table._component_args["data"][0].keys()) == 100+ assert table._component_args["field-types"] is None+++def test_column_clamping_with_small_data():+ data = {f"col{i}": [1, 2, 3] for i in range(10)}++ # Should not clamp when under max_columns+ table = ui.table(data)+ assert len(table._manager.get_column_names()) == 10+ assert table._component_args["total-columns"] == 10+ assert len(table._component_args["data"][0].keys()) == 10+ assert table._component_args["field-types"] is None+++def test_search_clamping_columns():+ data = {f"col{i}": [1, 2, 3] for i in range(100)}+ table = ui.table(data, max_columns=20)++ # Perform a search+ search_args = SearchTableArgs(page_size=10, page_number=0, query="1")+ response = table.search(search_args)++ # Check that the search result is clamped+ assert len(response.data[0].keys()) == 20++ # Check that selection is not clamped+ table._selected_manager = table._searched_manager.select_rows([0])+ selected_data = table._selected_manager.data+ assert len(selected_data) == 100+++def test_search_no_clamping_columns():+ data = {f"col{i}": [1, 2, 3] for i in range(100)}+ table = ui.table(data, max_columns=None)++ # Perform a search+ search_args = SearchTableArgs(page_size=10, page_number=0, query="1")+ response = table.search(search_args)++ # Check that the search result is not clamped+ assert len(response.data[0].keys()) == 100++ # Check that selection is not clamped+ table._selected_manager = table._searched_manager.select_rows([0])+ selected_data = table._selected_manager.data+ assert len(selected_data) == 100+++def test_column_clamping_with_exact_max_columns():+ data = {f"col{i}": [1, 2, 3] for i in range(50)}+ table = ui.table(data, max_columns=50)++ # Check that the table is not clamped+ assert len(table._manager.get_column_names()) == 50+ assert table._component_args["total-columns"] == 50+ assert len(table._component_args["data"][0].keys()) == 50+ assert table._component_args["field-types"] is None+++def test_column_clamping_with_more_than_max_columns():+ data = {f"col{i}": [1, 2, 3] for i in range(60)}+ table = ui.table(data, max_columns=50)++ # Check that the table is clamped+ assert len(table._manager.get_column_names()) == 60+ assert table._component_args["total-columns"] == 60+ assert len(table._component_args["data"][0].keys()) == 50+ assert table._component_args["field-types"] is None+++def test_column_clamping_with_no_columns():+ table = ui.table([], max_columns=50)++ # Check that the table handles no columns gracefully+ assert len(table._manager.get_column_names()) == 1+ assert table._component_args["total-columns"] == 1+ assert len(table._component_args["data"]) == 0+ assert table._component_args["field-types"] is None+++def test_column_clamping_with_single_column():+ data = {"col1": [1, 2, 3]}+ table = ui.table(data, max_columns=50)++ # Check that the table handles a single column gracefully+ assert len(table._manager.get_column_names()) == 1+ assert table._component_args["total-columns"] == 1+ assert len(table._component_args["data"][0].keys()) == 1+ assert table._component_args["field-types"] is None+++ not DependencyManager.polars.has(), reason="Polars not installed"+)+def test_column_clamping_with_polars():+ import polars as pl++ data = pl.DataFrame({f"col{i}": [1, 2, 3] for i in range(60)})+ table = ui.table(data)++ # Check that the table is clamped+ assert len(table._manager.get_column_names()) == 60+ assert table._component_args["total-columns"] == 60+ csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")+ headers = csv.split("\n")[0].split(",")+ assert len(headers) == 50 # 50 columns+ assert len(table._component_args["field-types"]) == 50++ table = ui.table(data, max_columns=40)++ # Check that the table is clamped+ assert len(table._manager.get_column_names()) == 60+ assert table._component_args["total-columns"] == 60+ csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")+ headers = csv.split("\n")[0].split(",")+ assert len(headers) == 40 # 40 columns+ assert len(table._component_args["field-types"]) == 40++ table = ui.table(data, max_columns=None)++ # Check that the table is not clamped+ assert len(table._manager.get_column_names()) == 60+ assert table._component_args["total-columns"] == 60+ csv = from_data_uri(table._component_args["data"])[1].decode("utf-8")+ headers = csv.split("\n")[0].split(",")+ assert len(headers) == 60 # 60 columns+ assert len(table._component_args["field-types"]) == 60