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: use variable name as download filename in dataframe viewer (#8227)
Ahmad Yasseraf37b9bea362
diff --git a/frontend/src/components/data-table/TableActions.tsx b/frontend/src/components/data-table/TableActions.tsxindex 689f65bbd8..d419e2398d 100644--- a/frontend/src/components/data-table/TableActions.tsx+++ b/frontend/src/components/data-table/TableActions.tsx@@ -30,6 +30,7 @@ interface TableActionsProps<TData> {onRowSelectionChange?: (value: RowSelectionState) => void;table: Table<TData>;downloadAs?: DownloadActionProps["downloadAs"];+ downloadFileName?: string;getRowIds?: GetRowIds;toggleDisplayHeader?: () => void;showChartBuilder?: boolean;@@ -52,6 +53,7 @@ export const TableActions = <TData,>({onRowSelectionChange,table,downloadAs,+ downloadFileName,getRowIds,toggleDisplayHeader,showChartBuilder,@@ -182,7 +184,12 @@ export const TableActions = <TData,>({/>)}<div className="ml-auto">- {downloadAs && <DownloadAs downloadAs={downloadAs} />}+ {downloadAs && (+ <DownloadAs+ downloadAs={downloadAs}+ downloadFileName={downloadFileName}+ />+ )}</div></div>);diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 3fba9d825a..b217dafc8a 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -116,6 +116,7 @@ const DataTableInternal = <TData,>({paginationState,setPaginationState,downloadAs,+ downloadFileName,manualPagination = false,pagination = false,onRowSelectionChange,@@ -334,6 +335,7 @@ const DataTableInternal = <TData,>({onRowSelectionChange={onRowSelectionChange}table={table}downloadAs={downloadAs}+ downloadFileName={downloadFileName}getRowIds={getRowIds}toggleDisplayHeader={toggleDisplayHeader}showChartBuilder={showChartBuilder}diff --git a/frontend/src/components/data-table/download-actions.tsx b/frontend/src/components/data-table/download-actions.tsxindex 3b13efe616..c9543556a3 100644--- a/frontend/src/components/data-table/download-actions.tsx+++ b/frontend/src/components/data-table/download-actions.tsx@@ -14,6 +14,7 @@ import { logNever } from "@/utils/assertNever";import { copyToClipboard } from "@/utils/copy";import { downloadByURL } from "@/utils/download";import { prettyError } from "@/utils/errors";+import { Filenames } from "@/utils/filenames";import {jsonParseWithSpecialChar,jsonToMarkdown,@@ -36,6 +37,7 @@ type DownloadFormat = "csv" | "json" | "parquet";export interface DownloadActionProps {downloadAs: (req: { format: DownloadFormat }) => Promise<string>;+ downloadFileName?: string;}const options = [@@ -158,7 +160,10 @@ export const DownloadAs: React.FC<DownloadActionProps> = (props) => {onSelect={async () => {const downloadUrl = await getDownloadUrl(option.format);const ext = option.format;- downloadByURL(downloadUrl, `download.${ext}`);+ const rawName = (props.downloadFileName ?? "").trim();+ const baseName =+ Filenames.withoutExtension(rawName) || "download";+ downloadByURL(downloadUrl, `${baseName}.${ext}`);}}><option.icon className="mo-dropdown-icon" />diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex fece947917..5f47ee33bc 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -195,6 +195,7 @@ interface Data<T> {hasStableRowId: boolean;lazy: boolean;cellHoverTexts?: Record<string, Record<string, string | null>> | null;+ downloadFileName?: string;}// eslint-disable-next-line @typescript-eslint/consistent-type-definitions@@ -278,6 +279,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")// If lazy, this will preload the first page of data// without user confirmation.preload: z.boolean().default(false),+ downloadFileName: z.string().optional(),}),).withFunctions<DataTableFunctions>({@@ -752,6 +754,7 @@ const DataTableComponent = ({cellStyles,hoverTemplate,cellHoverTexts,+ downloadFileName,toggleDisplayHeader,calculate_top_k_rows,preview_column,@@ -981,6 +984,7 @@ const DataTableComponent = ({hoverTemplate={hoverTemplate}cellHoverTexts={cellHoverTexts}downloadAs={showDownload ? downloadAs : undefined}+ downloadFileName={downloadFileName}enableSearch={enableSearch}searchQuery={searchQuery}onSearchQueryChange={setSearchQuery}diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex ee1b0a1acc..47d7f5a23f 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -48,6 +48,7 @@ type TableData<T> = T[] | CsvURL;interface Data {label?: string | null;columns: ColumnDataTypes;+ dataframeName?: string;pageSize: number;showDownload: boolean;lazy: boolean;@@ -93,6 +94,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")label: z.string().nullish(),pageSize: z.number().default(5),showDownload: z.boolean().default(true),+ dataframeName: z.string().optional(),columns: z.array(z.tuple([z.string().or(z.number()), z.string(), z.string()])).transform((value) => {@@ -176,6 +178,7 @@ const EMPTY: Transformations = {export const DataFrameComponent = memo(({columns,+ dataframeName,pageSize,showDownload,lazy,@@ -326,6 +329,7 @@ export const DataFrameComponent = memo(fieldTypes={field_types}rowHeaders={row_headers || Arrays.EMPTY}showDownload={showDownload}+ downloadFileName={dataframeName}download_as={download_as}enableSearch={false}showFilters={false}diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex 51f61c50b2..cad414709d 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -1,7 +1,6 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import inspectimport sysfrom dataclasses import dataclassfrom typing import (@@ -51,6 +50,7 @@ from marimo._utils.memoize import memoize_last_valuefrom marimo._utils.methods import getcallablefrom marimo._utils.narwhals_utils import is_narwhals_lazyframe, make_lazyfrom marimo._utils.parse_dataclass import parse_raw+from marimo._utils.variable_name import infer_variable_nameTOO_MANY_ROWS = 100_000@@ -147,20 +147,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):# This will raise an error if the dataframe type is not supported.handler = get_handler_for_dataframe(df)- # HACK: this is a hack to get the name of the variable that was passed- dataframe_name = "df"- try:- frame = inspect.currentframe()- if frame is not None and frame.f_back is not None:- for (- var_name,- var_value,- ) in frame.f_back.f_locals.items():- if var_value is df:- dataframe_name = var_name- break- except Exception:- pass+ dataframe_name = infer_variable_name(df, "df")# Make the dataframe lazy and keep an undo callback to restore original typenw_df, self._undo = make_lazy(df)diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 56c41b9398..a62ce49c57 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -71,6 +71,7 @@ from marimo._utils.narwhals_utils import (can_narwhalify_lazyframe,unwrap_narwhals_dataframe,)+from marimo._utils.variable_name import infer_variable_nameif TYPE_CHECKING:from collections.abc import Sequence@@ -502,6 +503,10 @@ class table(self._max_columns: Optional[int] = Nonemax_columns_arg: Union[int, str]+ # Infer the variable name before add_selection_column() mutates data,+ # so the identity check still matches the caller's original variable.+ download_file_name = infer_variable_name(data, "download")+has_stable_row_id = Falseif selection is not None:data, has_stable_row_id = add_selection_column(data)@@ -731,6 +736,7 @@ class table("max-height": int(max_height)if max_height is not Noneelse None,+ "download-file-name": download_file_name,},on_change=on_change,functions=(diff --git a/marimo/_utils/variable_name.py b/marimo/_utils/variable_name.pynew file mode 100644index 0000000000..70cf17d68b--- /dev/null+++ b/marimo/_utils/variable_name.py@@ -0,0 +1,38 @@+from __future__ import annotations++import inspect+from typing import Any++from marimo import _loggers++LOGGER = _loggers.marimo_logger()+++def infer_variable_name(value: Any, fallback: str) -> str:+ """Infer the variable name that holds ``value`` in the caller's caller.++ Walks up two frames (skipping this helper and the direct caller) and+ searches locals for an identity match (``is``). Returns *fallback* if+ the lookup fails for any reason.++ Frame references are always cleaned up to avoid reference cycles.+ """+ frame = None+ target_frame = None+ try:+ frame = inspect.currentframe()+ if frame is not None and frame.f_back is not None:+ target_frame = frame.f_back.f_back+ if target_frame is not None:+ for var_name, var_value in target_frame.f_locals.items():+ if var_value is value:+ return var_name+ except Exception:+ LOGGER.debug(+ "Failed to infer variable name from caller frame.",+ exc_info=True,+ )+ finally:+ del frame+ del target_frame+ return fallbackdiff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex cc9b9b0c70..ccd1ceeb84 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -1094,6 +1094,12 @@ class TestTableGetValueCounts:assert value_counts == [ValueCount(value="1", count=2)]+def test_table_download_file_name() -> None:+ my_data = {"a": [1, 2, 3]}+ t = ui.table(my_data)+ assert t._component_args["download-file-name"] == "my_data"++def test_table_with_frozen_columns() -> None:data = {"a": list(range(20)),