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
fix(download): allow lazy (callable) filename (#9799)
Kiran Gadhave9bcf78bc6188
diff --git a/frontend/src/plugins/layout/DownloadPlugin.tsx b/frontend/src/plugins/layout/DownloadPlugin.tsxindex 2e585e719c..9844f46d1e 100644--- a/frontend/src/plugins/layout/DownloadPlugin.tsx+++ b/frontend/src/plugins/layout/DownloadPlugin.tsx@@ -98,7 +98,7 @@ const DownloadButton = ({try {const loadedData = await load({});downloadByURL(- loadedData.data,+ loadedData.data || data.data,loadedData.filename ?? data.filename ?? undefined,);} catch (error) {diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.pyindex 54ae6c6906..b190fedd97 100644--- a/marimo/_plugins/stateless/download.py+++ b/marimo/_plugins/stateless/download.py@@ -41,7 +41,11 @@ class download(UIElement[None, None]):- file opened in binary mode- callable returning any of the above (for lazy loading)- async callable returning any of the above (for lazy loading)- filename (str): The name of the file to download.+ filename (str, callable): The name of the file to download. Can be a+ zero-arg callable returning a string, evaluated at click time so+ the name reflects the latest application state. A callable filename+ disables extension-based mimetype inference; pass `mimetype`+ explicitly if you need a specific one.If not provided, the name will be guessed from the data.mimetype (str): The mimetype of the file to download, for example,(e.g. "text/csv", "image/png"). If not provided,@@ -78,7 +82,7 @@ class download(UIElement[None, None]):data: DataType| Callable[[], DataType]| Callable[[], Coroutine[None, None, DataType]],- filename: str | None = None,+ filename: str | Callable[[], str] | None = None,mimetype: str | None = None,disabled: bool = False,*,@@ -89,10 +93,15 @@ class download(UIElement[None, None]):self._mimetype = mimetypedata_url = ""- is_lazy = callable(data)-- # name used to guess mimetype- name_for_mime = data if isinstance(data, str) else filename+ is_lazy = callable(data) or callable(filename)++ # name used to guess mimetype; a callable filename has no extension to+ # inspect at render time, so skip inference and fall back to text/plain+ name_for_mime = (+ data+ if isinstance(data, str)+ else (None if callable(filename) else filename)+ )resolved_mimetype = (mimetype or guess_mime_type(name_for_mime) or "text/plain")@@ -124,7 +133,7 @@ class download(UIElement[None, None]):on_change=None,args={"data": data_url,- "filename": filename,+ "filename": None if callable(filename) else filename,"disabled": disabled,"lazy": is_lazy,},@@ -140,23 +149,31 @@ class download(UIElement[None, None]):)async def _load(self, _args: EmptyArgs) -> LoadResponse:- if callable(self._data) and not isinstance(self._data, UIElement):+ filename = (+ self._filename() if callable(self._filename) else self._filename+ )++ # Eager data already ships as the button's href; a callable filename is+ # the only reason load runs here, so resolve the name and let the+ # frontend reuse the href instead of re-encoding the payload.+ if not callable(self._data):+ return LoadResponse(data="", filename=filename)++ if isinstance(self._data, UIElement):+ result = self._data+ else:result_or_coroutine = self._data()if asyncio.iscoroutine(result_or_coroutine):result = await result_or_coroutineelse:result = result_or_coroutine- else:- result = self._dataurl = io_to_data_url(result, fallback_mime_type=self._mimetype or "text/plain")-if url is None:raise ValueError("Failed to convert data to data URL")-- return LoadResponse(data=url, filename=self._filename)+ return LoadResponse(data=url, filename=filename)def _convert_value(self, value: None) -> None:return valuediff --git a/tests/_plugins/test_download.py b/tests/_plugins/test_download.pyindex 70a5226ecd..bc89966674 100644--- a/tests/_plugins/test_download.py+++ b/tests/_plugins/test_download.py@@ -191,3 +191,67 @@ async def test_download_xlsx_lazy_with_filename():)# Verify filename is preserved in lazy load responseassert loaded_data.filename == "output.xlsx"+++async def test_download_lazy_filename():+ """Test callable filename forces lazy path and resolves at click time."""+ result = download(b"test data", filename=lambda: "dynamic.xlsx")+ args = result._component_args+ # A callable filename forces the lazy path even with static data...+ assert args["lazy"]+ # ...and is not serialized into render args; load supplies it instead.+ assert args["filename"] is None++ loaded_data = await result._load(EmptyArgs())+ assert loaded_data.filename == "dynamic.xlsx"+++async def test_download_lazy_filename_evaluated_at_call():+ """Test the callable filename is evaluated per load, not at construction."""+ name = {"value": "first.txt"}+ result = download(b"test data", filename=lambda: name["value"])++ first = await result._load(EmptyArgs())+ assert first.filename == "first.txt"++ name["value"] = "second.txt"+ second = await result._load(EmptyArgs())+ assert second.filename == "second.txt"+++async def test_download_lazy_filename_with_lazy_data():+ """Test callable data and callable filename resolve together in load."""++ def get_data():+ return b"test data"++ result = download(data=get_data, filename=lambda: "dynamic.csv")+ args = result._component_args+ assert args["lazy"]+ assert args["filename"] is None++ loaded_data = await result._load(EmptyArgs())+ assert loaded_data.data.startswith("data:text/plain;base64")+ assert loaded_data.filename == "dynamic.csv"+++async def test_download_lazy_filename_eager_data_reuses_href():+ """Eager data ships as the href; load returns only the resolved name."""+ result = download(b"test data", filename=lambda: "dynamic.xlsx")+ args = result._component_args+ # Data URL is shipped eagerly for the frontend to reuse.+ assert args["data"].startswith("data:")++ loaded_data = await result._load(EmptyArgs())+ # No re-encode: load supplies the fresh name, the href carries the data.+ assert loaded_data.data == ""+ assert loaded_data.filename == "dynamic.xlsx"+++def test_download_lazy_filename_mimetype_fallback():+ """Test callable filename skips extension inference without raising."""+ # No extension to inspect at render time, so mimetype falls back to+ # text/plain rather than being guessed from the (unevaluated) callable.+ result = download(b"test data", filename=lambda: "dynamic.xlsx")+ args = result._component_args+ assert args["data"].startswith("data:text/plain;base64")