Skip to content

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.

fix(table): export menu works for plain-Python data without `pandas/polars/pyarrow` (#9246)

Kiran Gadhave0f934c1e5128
diff --git a/frontend/src/components/data-table/export-actions.tsx b/frontend/src/components/data-table/export-actions.tsx
index 5b0b1ff4b7..f80aabc37d 100644
--- a/frontend/src/components/data-table/export-actions.tsx
+++ b/frontend/src/components/data-table/export-actions.tsx
@@ -20,6 +20,7 @@ import {
jsonToMarkdown,
jsonToTSV,
} from "@/utils/json/json-parser";
+import { MissingPackagePrompt } from "../datasources/missing-package-prompt";
import { Button } from "../ui/button";
import {
DropdownMenu,
@@ -38,6 +39,8 @@ export interface ExportActionProps {
downloadAs: (req: { format: DownloadFormat }) => Promise<{
url: string;
filename: string;
+ error?: string | null;
+ missing_packages?: string[] | null;
}>;
}
@@ -81,6 +84,8 @@ const copyOptions = [
FILE_TYPES.CSV,
FILE_TYPES.MARKDOWN,
];
+const labelForDownloadFormat = (format: DownloadFormat): string =>
+ downloadOptions.find((opt) => opt.format === format)?.label ?? format;
export const ExportMenu: React.FC<ExportActionProps> = (props) => {
const { locale } = useLocale();
@@ -101,43 +106,82 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {
</Button>
);
- const getDownloadResult = (format: DownloadFormat) => {
- return props.downloadAs({ format }).catch((error) => {
+ const resolveDownloadUrl = async (
+ format: DownloadFormat,
+ onRetry: () => void,
+ ): Promise<{ url: string; filename: string } | null> => {
+ let response: Awaited<ReturnType<typeof props.downloadAs>>;
+ try {
+ response = await props.downloadAs({ format });
+ } catch (error) {
toast({
title: "Failed to download",
- description: "message" in error ? error.message : String(error),
+ description:
+ error != null && typeof error === "object" && "message" in error
+ ? String(error.message)
+ : String(error),
});
- throw error;
+ return null;
+ }
+
+ if (response.missing_packages && response.missing_packages.length > 0) {
+ toast({
+ title: "Export failed",
+ description: (
+ <MissingPackagePrompt
+ packages={response.missing_packages}
+ featureName={`${labelForDownloadFormat(format)} export`}
+ description={response.error}
+ onInstall={onRetry}
+ />
+ ),
+ });
+ return null;
+ }
+
+ return { url: response.url, filename: response.filename };
+ };
+
+ const handleDownload = async (format: DownloadFormat) => {
+ const result = await resolveDownloadUrl(format, () => {
+ void handleDownload(format);
});
+ if (!result) {
+ return;
+ }
+ const rawName = (result.filename ?? "").trim();
+ const baseName = Filenames.withoutExtension(rawName) || "download";
+ downloadByURL(result.url, `${baseName}.${format}`);
};
const handleClipboardCopy = async (
format: (typeof copyOptions)[number]["format"],
) => {
- let text: string;
+ const sourceFormat: DownloadFormat = format === "csv" ? "csv" : "json";
+ const result = await resolveDownloadUrl(sourceFormat, () => {
+ void handleClipboardCopy(format);
+ });
+ if (!result) {
+ return;
+ }
+ let text: string;
switch (format) {
case "tsv": {
- const { url } = await getDownloadResult("json");
- const json = await fetchJson(url);
+ const json = await fetchJson(result.url);
text = jsonToTSV(json, locale);
break;
}
case "json": {
- const { url } = await getDownloadResult("json");
- const json = await fetchJson(url);
+ const json = await fetchJson(result.url);
text = JSON.stringify(json, null, 2);
break;
}
- case "csv": {
- const { url } = await getDownloadResult("csv");
- const csv = await fetchText(url);
- text = csv;
+ case "csv":
+ text = await fetchText(result.url);
break;
- }
case "markdown": {
- const { url } = await getDownloadResult("json");
- const json = await fetchJson(url);
+ const json = await fetchJson(result.url);
text = jsonToMarkdown(json);
break;
}
@@ -164,13 +208,8 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {
{downloadOptions.map((option) => (
<DropdownMenuItem
key={option.label}
- onSelect={async () => {
- const { url, filename } = await getDownloadResult(option.format);
- const ext = option.format;
- const rawName = (filename ?? "").trim();
- const baseName =
- Filenames.withoutExtension(rawName) || "download";
- downloadByURL(url, `${baseName}.${ext}`);
+ onSelect={() => {
+ void handleDownload(option.format);
}}
>
<option.icon className="mo-dropdown-icon" />
diff --git a/frontend/src/components/data-table/schemas.ts b/frontend/src/components/data-table/schemas.ts
index 15790c5ffa..54a43e6f5d 100644
--- a/frontend/src/components/data-table/schemas.ts
+++ b/frontend/src/components/data-table/schemas.ts
@@ -5,7 +5,12 @@ import { rpc } from "@/plugins/core/rpc";
export type DownloadAsArgs = (req: {
format: "csv" | "json" | "parquet";
-}) => Promise<{ url: string; filename: string }>;
+}) => Promise<{
+ url: string;
+ filename: string;
+ error?: string | null;
+ missing_packages?: string[] | null;
+}>;
export const DownloadAsSchema = rpc
.input(
@@ -17,5 +22,7 @@ export const DownloadAsSchema = rpc
z.object({
url: z.string(),
filename: z.string(),
+ error: z.string().nullish(),
+ missing_packages: z.array(z.string()).nullish(),
}),
);
diff --git a/frontend/src/components/datasources/__tests__/missing-package-prompt.test.tsx b/frontend/src/components/datasources/__tests__/missing-package-prompt.test.tsx
new file mode 100644
index 0000000000..1338c9fa2b
--- /dev/null
+++ b/frontend/src/components/datasources/__tests__/missing-package-prompt.test.tsx
@@ -0,0 +1,103 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { render, screen } from "@testing-library/react";
+import { Provider } from "jotai";
+import React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { viewStateAtom } from "@/core/mode";
+import { requestClientAtom } from "@/core/network/requests";
+import { store } from "@/core/state/jotai";
+import { MissingPackagePrompt } from "../missing-package-prompt";
+
+const mockOpenApplication = vi.fn();
+vi.mock("@/components/editor/chrome/state", () => ({
+ useChromeActions: () => ({
+ openApplication: mockOpenApplication,
+ }),
+}));
+
+vi.mock("@/components/editor/chrome/panels/packages-state", () => ({
+ packagesToInstallAtom: {},
+}));
+
+const mockRequestAnimationFrame = vi.fn((callback) => {
+ callback();
+ return 1;
+});
+vi.stubGlobal("requestAnimationFrame", mockRequestAnimationFrame);
+
+const mockInput = {
+ focus: vi.fn(),
+ value: "",
+ dispatchEvent: vi.fn(),
+};
+vi.spyOn(document, "getElementById").mockReturnValue(
+ mockInput as unknown as HTMLInputElement,
+);
+
+function createTestWrapper() {
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <Provider store={store}>{children}</Provider>
+ );
+ return { wrapper };
+}
+
+describe("MissingPackagePrompt", () => {
+ const { wrapper } = createTestWrapper();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store.set(requestClientAtom, MockRequestClient.create());
+ store.set(viewStateAtom, { mode: "edit", cellAnchor: null });
+ });
+
+ it("should render backend description and install button in edit mode", () => {
+ render(
+ <MissingPackagePrompt
+ packages={["polars"]}
+ featureName="Parquet export"
+ description="Parquet export requires a DataFrame library."
+ />,
+ { wrapper },
+ );
+ expect(
+ screen.getByText("Parquet export requires a DataFrame library."),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Install polars")).toBeInTheDocument();
+ });
+
+ it("should fall back to generic copy when description is absent", () => {
+ render(
+ <MissingPackagePrompt
+ packages={["polars"]}
+ featureName="Parquet export"
+ />,
+ { wrapper },
+ );
+ expect(
+ screen.getByText("Parquet export requires polars"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Install polars")).toBeInTheDocument();
+ });
+
+ it("should render generic line in read mode and not leak packages or description", () => {
+ store.set(viewStateAtom, { mode: "read", cellAnchor: null });
+ render(
+ <MissingPackagePrompt
+ packages={["polars"]}
+ featureName="Parquet export"
+ description="Install polars to enable Parquet."
+ />,
+ { wrapper },
+ );
+ expect(
+ screen.getByText("Parquet export isn't available in this notebook"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText("Install polars to enable Parquet."),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText("Install polars")).not.toBeInTheDocument();
+ expect(screen.queryByText(/polars/)).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/datasources/missing-package-prompt.tsx b/frontend/src/components/datasources/missing-package-prompt.tsx
new file mode 100644
index 0000000000..47041e71b7
--- /dev/null
+++ b/frontend/src/components/datasources/missing-package-prompt.tsx
@@ -0,0 +1,49 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useInstallAllowed } from "@/core/mode";
+import { cn } from "@/utils/cn";
+import { InstallPackageButton } from "./install-package-button";
+
+interface MissingPackagePromptProps {
+ packages: string[];
+ featureName: string;
+ description?: string | null; // server message, suppressing this in read-only mode
+ onInstall?: () => void;
+ className?: string;
+}
+
+/**
+ * display missing-package requirement with mode-aware copy. In edit mode,
+ * shows the backend explanation (if any) plus an install button for missing-packages.
+ * read mode, shows a generic "isn't available"
+ */
+export const MissingPackagePrompt: React.FC<MissingPackagePromptProps> = ({
+ packages,
+ featureName,
+ description,
+ onInstall,
+ className,
+}) => {
+ const installAllowed = useInstallAllowed();
+
+ if (!installAllowed) {
+ return (
+ <span className={cn("text-xs", className)}>
+ {featureName} isn't available in this notebook
+ </span>
+ );
+ }
+
+ return (
+ <div className={cn("text-xs flex flex-col items-end gap-2", className)}>
+ <span className="self-start">
+ {description || `${featureName} requires ${packages.join(", ")}`}
+ </span>
+ <InstallPackageButton
+ packages={packages}
+ onInstall={onInstall}
+ className="ml-0"
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/core/mode.ts b/frontend/src/core/mode.ts
index 80cfa5cdca..a16172ae66 100644
--- a/frontend/src/core/mode.ts
+++ b/frontend/src/core/mode.ts
@@ -1,6 +1,6 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { atom } from "jotai";
+import { atom, useAtomValue } from "jotai";
import { isIslands } from "@/core/islands/utils";
import { assertExists } from "@/utils/assertExists";
import { invariant } from "@/utils/invariant";
@@ -79,3 +79,12 @@ export const viewStateAtom = atom<ViewState>({
export const initialModeAtom = atom<AppMode | undefined>(undefined);
export const kioskModeAtom = atom<boolean>(false);
+
+/**
+ * Whether installing packages is allowed in the current view. False in read
+ * mode, since end-users of a deployed notebook cannot mutate its environment.
+ */
+export function useInstallAllowed(): boolean {
+ const { mode } = useAtomValue(viewStateAtom);
+ return mode !== "read";
+}
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index af1720bd97..057d8ef51f 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -97,8 +97,13 @@ class DownloadAsArgs:
@dataclass
class DownloadAsResponse:
- url: str
- filename: str
+ url: str = ""
+ filename: str = ""
+ # Populated when the requested format's dependencies are missing (e.g.,
+ # Parquet without pyarrow/pandas/polars). Mirrors the shape used by
+ # ColumnPreview so the frontend can reuse its install-prompt flow.
+ error: str | None = None
+ missing_packages: list[str] | None = None
@dataclass
@@ -873,16 +878,52 @@ class table(
current searched/filtered view. Raw data is downloaded without any
formatting applied.
+ When a requested format requires a package that isn't installed
+ (e.g., Parquet without pyarrow/pandas/polars), returns a
+ ``DownloadAsResponse`` with ``error`` and ``missing_packages``
+ populated instead of raising. The frontend uses this to prompt the
+ user to install the dependency and retry.
+
Args:
- args (DownloadAsArgs): Arguments specifying the download format.
- format must be one of 'csv' or 'json'.
+ args (DownloadAsArgs): The requested download format. Must be
+ one of ``'csv'``, ``'json'``, or ``'parquet'``.
Returns:
- DownloadAsResponse: URL and filename for the downloaded file.
+ DownloadAsResponse: Either a success response with ``url`` and
+ ``filename`` populated, or a missing-packages response with
+ ``error`` and ``missing_packages`` populated when the
+ format's dependencies are not available.
Raises:
- ValueError: If format is not 'csv' or 'json'.
+ NotImplementedError: If the current selection resolves to
+ something other than a ``TableManager`` (e.g., a raw list
+ of ``TableCell`` from cell-selection modes).
"""
+ # Short-circuit Parquet when no parquet-capable lib is importable.
+ if args.format == "parquet":
+ has_polars = DependencyManager.polars.has()
+ has_pandas = DependencyManager.pandas.has()
+ has_pyarrow = DependencyManager.pyarrow.has()
+
+ if not (has_polars or (has_pandas and has_pyarrow)):
+ # if pandas is installed and pyarrow is not, prompt to install pyarrow
+ if has_pandas:
+ return DownloadAsResponse(
+ error=(
+ "Parquet export requires pyarrow. "
+ "Please install pyarrow to enable parquet export."
+ ),
+ missing_packages=["pyarrow"],
+ )
+ else: # else prompt polars
+ return DownloadAsResponse(
+ error=(
+ "Parquet export requires a DataFrame library. "
+ "We recommend polars."
+ ),
+ missing_packages=["polars"],
+ )
+
# For cell-selection modes, ignore selection and download from the
# searched/filtered view. For row-selection modes, preserve existing
# behavior: download selected rows if any, otherwise the searched view.
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index 70e23fae91..91c957a901 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -55,14 +55,6 @@ class DefaultTableManager(TableManager[JsonTableData]):
self.data = data
self.is_column_oriented = _is_column_oriented(data)
- def supports_download(self) -> bool:
- # If we have pandas/polars/pyarrow, we can convert to CSV or JSON
- return (
- DependencyManager.pandas.has()
- or DependencyManager.polars.has()
- or DependencyManager.pyarrow.has()
- )
-
def apply_formatting(
self, format_mapping: FormatMapping | None
) -> TableManager[JsonTableData]:
@@ -95,14 +87,26 @@ class DefaultTableManager(TableManager[JsonTableData]):
format_mapping: FormatMapping | None = None,
separator: str | None = None,
) -> str:
- if isinstance(self.data, dict) and not self.is_column_oriented:
- return DefaultTableManager(
- self._normalize_data(self.data)
- ).to_csv_str(format_mapping, separator=separator)
-
- return self._as_table_manager().to_csv_str(
- format_mapping, separator=separator
+ import csv
+ import io
+
+ formatted = self.apply_formatting(format_mapping)
+ rows = self._normalize_data(formatted.data)
+ columns = self.get_column_names()
+ buf = io.StringIO()
+
+ writer = csv.DictWriter(
+ buf,
+ fieldnames=columns,
+ delimiter=separator or ",",
+ lineterminator="\n",
+ )
+ writer.writeheader()
+ writer.writerows(
+ {col: _to_csv_cell(row.get(col)) for col in columns}
+ for row in rows
)
+ return buf.getvalue()
def to_json_str(
self,
@@ -504,3 +508,11 @@ def _is_column_oriented(data: JsonTableData) -> bool:
return isinstance(data, dict) and all(
isinstance(value, (list, tuple)) for value in data.values()
)
+
+
+def _to_csv_cell(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, (dict, list, tuple)):
+ return str(encode_json_str(SuperJson(value)))
+ return str(value)
diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.py
index 14748733a8..9b6a04d009 100644
--- a/tests/_plugins/ui/_impl/tables/test_default_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py
@@ -490,6 +490,26 @@ class TestDefaultTable(unittest.TestCase):
expected_data = [(date(1994, 5, 24), 2), (None, 2)]
assert result == expected_data
+ def test_supports_download(self) -> None:
+ assert self.manager.supports_download() is True
+
+ def test_to_csv(self) -> None:
+ manager = DefaultTableManager([{"a": 1, "b": 2}, {"a": 3, "b": 4}])
+ assert manager.to_csv() == b"a,b\n1,2\n3,4\n"
+
+ def test_to_csv_with_separator(self) -> None:
+ manager = DefaultTableManager([{"a": 1, "b": 2}])
+ assert manager.to_csv(separator="\t") == b"a\tb\n1\t2\n"
+
+ def test_to_csv_handles_none_and_nested(self) -> None:
+ manager = DefaultTableManager(
+ [{"a": None, "b": {"k": "v"}, "c": [1, 2]}]
+ )
+ result = manager.to_csv().decode()
+ # None renders as an empty cell; nested values render as JSON
+ # strings (quoted/escaped by the csv module).
+ assert result == 'a,b,c\n,"{""k"":""v""}","[1,2]"\n'
+
class TestColumnarDefaultTable(unittest.TestCase):
def setUp(self) -> None:
@@ -883,9 +903,6 @@ class TestColumnarDefaultTable(unittest.TestCase):
]
assert result == expected_data
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
def test_to_csv(self) -> None:
manager = DefaultTableManager(
{
@@ -893,10 +910,7 @@ class TestColumnarDefaultTable(unittest.TestCase):
"b": [3, 4],
}
)
- result = manager.to_csv()
- assert (
- result == b"a,b\n1,3\n2,4\n" or result == b"a,b\r\n1,3\r\n2,4\r\n"
- )
+ assert manager.to_csv() == b"a,b\n1,3\n2,4\n"
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
@@ -1103,14 +1117,8 @@ class TestDictionaryDefaultTable(unittest.TestCase):
expected_data = [(None, 2), ("A", 1)]
assert result == expected_data
- @pytest.mark.skipif(
- not HAS_DEPS, reason="optional dependencies not installed"
- )
def test_to_csv(self) -> None:
- result = self.manager.to_csv()
- assert result == b"key,value\na,1\nb,2\n" or result == (
- b"key,value\r\na,1\r\nb,2\r\n"
- )
+ assert self.manager.to_csv() == b"key,value\na,1\nb,2\n"
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
@@ -1136,6 +1144,9 @@ class TestListDefaultTable(unittest.TestCase):
TableCell(row=2, column="value", value=6),
]
+ def test_to_csv(self) -> None:
+ assert self.manager.to_csv() == b"value\n4\n5\n6\n"
+
@pytest.mark.skipif(
not HAS_DEPS, reason="optional dependencies not installed"
)
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 81fcdb8c80..7d86785e9f 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -1376,6 +1376,40 @@ def test_download_as_ignores_cell_selection() -> None:
assert int(rows[0]["a"]) == 2
+def test_download_as_parquet_without_libs_reports_missing_packages(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(DependencyManager.pandas, "has", lambda: False)
+ monkeypatch.setattr(DependencyManager.polars, "has", lambda: False)
+ monkeypatch.setattr(DependencyManager.pyarrow, "has", lambda: False)
+
+ table = ui.table([{"a": 1}])
+ response = table._download_as(DownloadAsArgs(format="parquet"))
+
+ assert response.url == ""
+ assert response.filename == ""
+ assert response.missing_packages == ["polars"]
+ assert response.error is not None
+ assert "polars" in response.error
+
+
+def test_download_as_parquet_with_pandas_only_prompts_pyarrow(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(DependencyManager.pandas, "has", lambda: True)
+ monkeypatch.setattr(DependencyManager.polars, "has", lambda: False)
+ monkeypatch.setattr(DependencyManager.pyarrow, "has", lambda: False)
+
+ table = ui.table([{"a": 1}])
+ response = table._download_as(DownloadAsArgs(format="parquet"))
+
+ assert response.url == ""
+ assert response.filename == ""
+ assert response.missing_packages == ["pyarrow"]
+ assert response.error is not None
+ assert "pyarrow" in response.error
+
+
@pytest.mark.skipif(
not DependencyManager.pandas.has() or not DependencyManager.polars.has(),
reason="Pandas or Polars not installed",