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.

improvement: better support for polars LazyFrame, mo.ui.table.lazy(df) (#4439)

Myles Scolnick3c1120987b0a
diff --git a/development_docs/traces.md b/development_docs/traces.md
index 471904422e..06397c06fe 100644
--- a/development_docs/traces.md
+++ b/development_docs/traces.md
@@ -30,4 +30,4 @@ marimo edit --profile-dir profiles/ notebook.py
If the notebook exits gracefully (i.e., is shut down manually), profiling
statistics will be written to the profiles/ directory. You can then use
standard tools to analyze the dumped statistics. To view flamegraphs,
-we recommend snakeviz or tuna (`pip install snakeviz; snakeviz path_to_profile`)
+we recommend snakeviz or tuna (`uvx snakeviz path_to_profile`)
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 0d16cfb39b..3ed6440988 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -47,6 +47,8 @@ import { DATA_TYPES } from "@/core/kernel/messages";
import { useEffectSkipFirstRender } from "@/hooks/useEffectSkipFirstRender";
import type { CellSelectionState } from "@/components/data-table/cell-selection/types";
import type { CellStyleState } from "@/components/data-table/cell-styling/types";
+import { Button } from "@/components/ui/button";
+import { Table2Icon } from "lucide-react";
type CsvURL = string;
type TableData<T> = T[] | CsvURL;
@@ -86,6 +88,7 @@ interface Data<T> {
wrappedColumns?: string[];
totalColumns: number;
hasStableRowId: boolean;
+ lazy: boolean;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
@@ -103,7 +106,7 @@ type DataTableFunctions = {
page_size: number;
}) => Promise<{
data: TableData<T>;
- total_rows: number;
+ total_rows: number | "too_many";
cell_styles?: CellStyleState | null;
}>;
get_row_ids?: GetRowIds;
@@ -150,6 +153,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
totalColumns: z.number(),
hasStableRowId: z.boolean().default(false),
cellStyles: z.record(z.record(z.object({}).passthrough())).optional(),
+ lazy: z.boolean(),
}),
)
.withFunctions<DataTableFunctions>({
@@ -190,7 +194,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
.output(
z.object({
data: z.union([z.string(), z.array(z.object({}).passthrough())]),
- total_rows: z.number(),
+ total_rows: z.union([z.number(), z.literal("too_many")]),
cell_styles: z
.record(z.record(z.object({}).passthrough()))
.nullable(),
@@ -207,18 +211,42 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
.renderer((props) => {
return (
<TooltipProvider>
- <LoadingDataTableComponent
- {...props.data}
- {...props.functions}
- enableSearch={true}
- data={props.data.data}
- value={props.value}
- setValue={props.setValue}
- />
+ <LazyDataTableComponent isLazy={props.data.lazy}>
+ <LoadingDataTableComponent
+ {...props.data}
+ {...props.functions}
+ enableSearch={true}
+ data={props.data.data}
+ value={props.value}
+ setValue={props.setValue}
+ />
+ </LazyDataTableComponent>
</TooltipProvider>
);
});
+const LazyDataTableComponent = ({
+ isLazy: initialIsLazy,
+ children,
+}: {
+ isLazy: boolean;
+ children: React.ReactNode;
+}) => {
+ const [isLazy, setIsLazy] = useState(initialIsLazy);
+
+ if (isLazy) {
+ return (
+ <div className="flex h-20 items-center justify-center">
+ <Button variant="outline" size="xs" onClick={() => setIsLazy(false)}>
+ <Table2Icon className="mr-2 h-4 w-4" />
+ Preview data
+ </Button>
+ </div>
+ );
+ }
+ return children;
+};
+
interface DataTableProps<T> extends Data<T>, DataTableFunctions {
className?: string;
// Selection
@@ -305,7 +333,8 @@ export const LoadingDataTableComponent = memo(
searchQuery === "" &&
paginationState.pageIndex === 0 &&
filters.length === 0 &&
- sorting.length === 0;
+ sorting.length === 0 &&
+ !props.lazy;
if (sorting.length > 1) {
Logger.warn("Multiple sort columns are not supported");
@@ -371,6 +400,7 @@ export const LoadingDataTableComponent = memo(
searchQuery,
useDeepCompareMemoize(props.fieldTypes),
props.data,
+ props.lazy,
paginationState.pageSize,
paginationState.pageIndex,
]);
@@ -586,12 +616,12 @@ const DataTableComponent = ({
<>
{/* // HACK: We assume "too_many" is coming from a SQL table */}
{totalRows === "too_many" && (
- <Banner className="mb-2 rounded">
- Result clipped. If no LIMIT is given, we only show the first 300 rows.
+ <Banner className="mb-1 rounded">
+ Previewing the first {paginationState.pageSize} rows.
</Banner>
)}
- {shownColumns < totalColumns && (
- <Banner className="mb-2 rounded">
+ {shownColumns < totalColumns && shownColumns > 0 && (
+ <Banner className="mb-1 rounded">
Result clipped. Showing {shownColumns} of {totalColumns} columns.
</Banner>
)}
@@ -599,7 +629,7 @@ const DataTableComponent = ({
// 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
// error information from the backend
- <Banner className="mb-2 rounded">
+ <Banner className="mb-1 rounded">
Column summaries are unavailable. Filter your data to fewer than
1,000,000 rows.
</Banner>
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 0d89cd7a2e..6f8c97500b 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -279,6 +279,7 @@ export const DataFrameComponent = memo(
value={Arrays.EMPTY}
setValue={Functions.NOOP}
selection={null}
+ lazy={false}
/>
</div>
);
diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.py
index 1ab9f99b57..f7eac921e0 100644
--- a/marimo/_data/preview_column.py
+++ b/marimo/_data/preview_column.py
@@ -3,6 +3,8 @@ from __future__ import annotations
from typing import Any, Optional
+import narwhals.stable.v1 as nw
+
from marimo import _loggers
from marimo._data.charts import get_chart_builder
from marimo._data.models import ColumnSummary
@@ -219,6 +221,9 @@ def _get_altair_chart(
try:
# Filter the data to the column we want
column_data = table.select_columns([request.column_name]).data
+ if isinstance(column_data, nw.LazyFrame):
+ column_data = column_data.collect()
+
chart_spec = _get_chart_spec(
column_data=column_data,
column_type=column_type,
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index 0569b678b5..5e05ef4970 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -4,6 +4,8 @@ from __future__ import annotations
from marimo import _loggers
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._output.md import md
+from marimo._plugins.ui._impl import tabs
from marimo._plugins.ui._impl.table import table
LOGGER = _loggers.marimo_logger()
@@ -58,6 +60,17 @@ class PolarsFormatter(FormatterFactory):
LOGGER.warning("Failed to format Series: %s", e)
return ("text/html", series._repr_html_())
+ @formatting.opinionated_formatter(pl.LazyFrame)
+ def _show_marimo_lazyframe(
+ df: pl.LazyFrame,
+ ) -> tuple[KnownMimeType, str]:
+ return tabs.tabs(
+ {
+ "Table": table.lazy(df),
+ "Query plan": md(df._repr_html_()),
+ }
+ )._mime_()
+
class PyArrowFormatter(FormatterFactory):
@staticmethod
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 1bc7d85c5b..42bf32167c 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -8,6 +8,7 @@ from typing import (
Any,
Callable,
Final,
+ Literal,
Optional,
Union,
)
@@ -46,7 +47,7 @@ from marimo._utils.parse_dataclass import parse_raw
@dataclass
class GetDataFrameResponse:
url: str
- total_rows: int
+ total_rows: Union[int, Literal["too_many"]]
# List of column names that are actually row headers
# This really only applies to Pandas, that has special index columns
row_headers: list[str]
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 1b0c7be9e7..89bf77a49f 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -11,9 +11,11 @@ from typing import (
Literal,
Optional,
Union,
+ cast,
)
-from narwhals.typing import IntoDataFrame
+import narwhals.stable.v1 as nw
+from narwhals.typing import IntoDataFrame, IntoLazyFrame
import marimo._output.data.data as mo_data
from marimo import _loggers
@@ -36,6 +38,7 @@ from marimo._plugins.ui._impl.tables.selection import (
)
from marimo._plugins.ui._impl.tables.table_manager import (
ColumnName,
+ FieldTypes,
RowId,
TableCell,
TableCoordinate,
@@ -100,7 +103,7 @@ CellStyles = dict[RowId, dict[ColumnName, dict[str, Any]]]
@dataclass(frozen=True)
class SearchTableResponse:
data: Union[JSONType, str]
- total_rows: int
+ total_rows: Union[int, Literal["too_many"]]
cell_styles: Optional[CellStyles] = None
@@ -117,6 +120,9 @@ class GetRowIdsResponse:
error: Optional[str] = None
+LAZY_PREVIEW_ROWS = 10
+
+
@mddoc
class table(
UIElement[
@@ -263,6 +269,43 @@ class table(
_name: Final[str] = "marimo-table"
+ @staticmethod
+ def lazy(data: IntoLazyFrame) -> table:
+ """
+ Create a table from a Polars LazyFrame.
+
+ This won't load the data into memory until requested by the user.
+ Once requested, only the first 10 rows will be loaded.
+
+ Pagination and selection are not supported for lazy tables.
+ """
+
+ if not nw.dependencies.is_polars_lazyframe(data):
+ raise ValueError("data must be a Polars LazyFrame")
+
+ return table(
+ data=data,
+ pagination=False,
+ selection=None,
+ initial_selection=None,
+ page_size=LAZY_PREVIEW_ROWS,
+ show_column_summaries=False,
+ show_download=False,
+ format_mapping=None,
+ freeze_columns_left=None,
+ freeze_columns_right=None,
+ text_justify_columns=None,
+ wrapped_columns=None,
+ label="",
+ on_change=None,
+ style_cell=None,
+ max_columns=50,
+ _internal_column_charts_row_limit=None,
+ _internal_summary_row_limit=None,
+ _internal_total_rows="too_many",
+ _internal_lazy=True,
+ )
+
def __init__(
self,
data: Union[
@@ -314,9 +357,11 @@ class table(
_internal_column_charts_row_limit: Optional[int] = None,
_internal_summary_row_limit: Optional[int] = None,
_internal_total_rows: Optional[Union[int, Literal["too_many"]]] = None,
+ _internal_lazy: bool = False,
) -> None:
validate_no_integer_columns(data)
validate_page_size(page_size)
+ self._lazy = _internal_lazy
has_stable_row_id = False
if selection is not None:
@@ -388,31 +433,27 @@ class table(
)
try:
if selection in ["single-cell", "multi-cell"]:
- coordinates = []
+ coordinates: list[TableCoordinate] = []
for v in initial_selection:
if not isinstance(v, tuple) or len(v) != 2:
raise TypeError(
"initial_selection must be a list of tuples for cell selection"
)
- else:
- coordinates.append(
- TableCoordinate(
- row_id=v[0],
- column_name=v[1],
- )
- )
- self._selected_manager = (
- self._searched_manager.select_cells(coordinates)
- )
+ coordinates.append(
+ TableCoordinate(row_id=v[0], column_name=v[1])
+ )
+ if coordinates:
+ self._selected_manager = (
+ self._searched_manager.select_cells(coordinates)
+ )
else:
- indexes = []
+ indexes: list[int] = []
for v in initial_selection:
if not isinstance(v, int):
raise TypeError(
"initial_selection must be a list of integers for row selection"
)
- else:
- indexes.append(v)
+ indexes.append(v)
self._selected_manager = (
self._searched_manager.select_rows(indexes)
)
@@ -435,8 +476,6 @@ class table(
# We will need this when calling table manager's to_data()
self._format_mapping = format_mapping
- field_types = self._manager.get_field_types()
-
if pagination is False and total_rows != "too_many":
page_size = total_rows
# pagination defaults to True if there are more than page_size rows
@@ -450,38 +489,49 @@ class table(
self._style_cell = style_cell
- # Search first page
- search_result = self._search(
- SearchTableArgs(
- page_size=page_size,
- page_number=0,
- query=None,
- sort=None,
- filters=None,
+ search_result_styles: Optional[CellStyles] = None
+ search_result_data: JSONType = []
+ field_types: Optional[FieldTypes] = None
+ num_columns = 0
+
+ if not _internal_lazy:
+ # Search first page
+ search_result = self._search(
+ SearchTableArgs(
+ page_size=page_size,
+ page_number=0,
+ query=None,
+ sort=None,
+ filters=None,
+ )
+ )
+ search_result_styles = search_result.cell_styles
+ search_result_data = search_result.data
+
+ # Validate column configurations
+ column_names_set = set(self._manager.get_column_names())
+ num_columns = len(column_names_set)
+ _validate_frozen_columns(
+ freeze_columns_left, freeze_columns_right, column_names_set
+ )
+ _validate_column_formatting(
+ text_justify_columns, wrapped_columns, column_names_set
)
- )
-
- column_names_set = set(self._manager.get_column_names())
-
- # Validate column configurations
- _validate_frozen_columns(
- freeze_columns_left, freeze_columns_right, column_names_set
- )
- _validate_column_formatting(
- text_justify_columns, wrapped_columns, column_names_set
- )
- # Clamp field types to max columns
- field_types = _get_clamped_field_types(field_types, self._max_columns)
+ # Clamp field types to max columns
+ field_types = self._manager.get_field_types()
+ field_types = _get_clamped_field_types(
+ field_types, self._max_columns
+ )
super().__init__(
component_name=table._name,
label=label,
initial_value=initial_value,
args={
- "data": search_result.data,
+ "data": search_result_data,
"total-rows": total_rows,
- "total-columns": self._manager.get_num_columns(),
+ "total-columns": num_columns,
"banner-text": self._get_banner_text(),
"pagination": pagination,
"page-size": page_size,
@@ -499,7 +549,8 @@ class table(
"text-justify-columns": text_justify_columns,
"wrapped-columns": wrapped_columns,
"has-stable-row-id": self._has_stable_row_id,
- "cell-styles": search_result.cell_styles,
+ "cell-styles": search_result_styles,
+ "lazy": _internal_lazy,
},
on_change=on_change,
functions=(
@@ -539,6 +590,9 @@ class table(
return self._data
def _get_banner_text(self) -> str:
+ if self._lazy:
+ return f"Previewing only the first {LAZY_PREVIEW_ROWS} rows."
+
total_columns = self._manager.get_num_columns()
if self._max_columns is not None and total_columns > self._max_columns:
return (
@@ -549,6 +603,9 @@ class table(
def _convert_value(
self, value: Union[list[int], list[str], list[dict[str, Any]]]
) -> Union[list[JSONType], IntoDataFrame, list[TableCell]]:
+ if self._selection is None:
+ return cast(list[JSONType], None)
+
if self._selection in ["single-cell", "multi-cell"]:
coordinates = [
TableCoordinate(row_id=v["rowId"], column_name=v["columnName"])
@@ -791,9 +848,14 @@ class table(
# If no query or sort, return nothing
# The frontend will just show the original data
+ total_rows: Union[int, Literal["too_many"]]
if not args.query and not args.sort and not args.filters:
self._searched_manager = self._manager
- total_rows = self._manager.get_num_rows(force=True) or 0
+ if self._lazy:
+ total_rows = "too_many"
+ else:
+ total_rows = self._manager.get_num_rows(force=True) or 0
+
return SearchTableResponse(
data=clamp_rows_and_columns(self._manager),
total_rows=total_rows,
@@ -801,7 +863,9 @@ class table(
# we need to check this is not larger than our actual number of rows.
cell_styles=self._style_cells(
offset,
- min(total_rows, args.page_size),
+ min(total_rows, args.page_size)
+ if total_rows != "too_many"
+ else args.page_size,
),
)
@@ -815,9 +879,14 @@ class table(
# Save the manager to be used for selection
self._searched_manager = result
+ if self._lazy:
+ total_rows = "too_many"
+ else:
+ total_rows = result.get_num_rows(force=True) or 0
+
return SearchTableResponse(
data=clamp_rows_and_columns(result),
- total_rows=result.get_num_rows(force=True) or 0,
+ total_rows=total_rows,
cell_styles=self._style_cells(offset, args.page_size),
)
diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.py
index c5451ced9e..798335256e 100644
--- a/marimo/_plugins/ui/_impl/tables/default_table.py
+++ b/marimo/_plugins/ui/_impl/tables/default_table.py
@@ -138,6 +138,9 @@ class DefaultTableManager(TableManager[JsonTableData]):
)
def select_cells(self, cells: list[TableCoordinate]) -> list[TableCell]:
+ if not cells:
+ return []
+
selected_cells: list[TableCell] = []
if (
self.is_column_oriented
diff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.py
index 76ed356111..4e208780bc 100644
--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py
+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py
@@ -77,8 +77,9 @@ class IbisTableManagerFactory(TableManagerFactory):
return IbisTableManager(self.data.select(columns))
def select_cells(
- self, _cells: list[TableCoordinate]
+ self, cells: list[TableCoordinate]
) -> list[TableCell]:
+ del cells
raise NotImplementedError("Cell selection not supported")
def drop_columns(
diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
index f79ad761d1..d7fd83c2b0 100644
--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py
+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py
@@ -105,6 +105,9 @@ class NarwhalsTableManager(
return True
def select_rows(self, indices: list[int]) -> TableManager[Any]:
+ if not indices:
+ return self.with_new_data(self.data.head(0))
+
df = self.as_frame()
# Prefer the index column for selections
if INDEX_COLUMN_NAME in df.columns:
@@ -118,6 +121,9 @@ class NarwhalsTableManager(
return self.with_new_data(self.data.select(columns))
def select_cells(self, cells: list[TableCoordinate]) -> list[TableCell]:
+ if not cells:
+ return []
+
df = self.as_frame()
if INDEX_COLUMN_NAME in df.columns:
selection: list[TableCell] = []
@@ -153,7 +159,7 @@ class NarwhalsTableManager(
@cached_property
def nw_schema(self) -> nw.Schema:
- return cast(nw.Schema, self.data.schema)
+ return cast(nw.Schema, self.data.collect_schema())
def get_field_type(
self, column_name: str
@@ -186,7 +192,11 @@ class NarwhalsTableManager(
raise ValueError("Count must be a positive integer")
if offset < 0:
raise ValueError("Offset must be a non-negative integer")
- return self.with_new_data(self.data[offset : offset + count])
+
+ if offset == 0:
+ return self.with_new_data(self.data.head(count))
+ else:
+ return self.with_new_data(self.data[offset : offset + count])
def search(self, query: str) -> TableManager[Any]:
query = query.lower()
@@ -233,7 +243,11 @@ class NarwhalsTableManager(
# If column is not in the dataframe, return an empty summary
if column not in self.nw_schema:
return ColumnSummary()
- col = self.data[column]
+ data = self.data.select(column)
+ if isinstance(data, nw.LazyFrame):
+ data = data.collect()
+
+ col = data[column]
total = len(col)
if is_narwhals_string_type(col.dtype):
return ColumnSummary(
@@ -354,6 +368,10 @@ class NarwhalsTableManager(
return self.data[column].cast(nw.String).unique().to_list()
def get_sample_values(self, column: str) -> list[str | int | float]:
+ # Skip lazy frames
+ if isinstance(self.data, nw.LazyFrame):
+ return []
+
# Sample 3 values from the column
SAMPLE_SIZE = 3
try:
diff --git a/marimo/_smoke_tests/tables/lazy_polars.py b/marimo/_smoke_tests/tables/lazy_polars.py
new file mode 100644
index 0000000000..5f80ee7ef8
--- /dev/null
+++ b/marimo/_smoke_tests/tables/lazy_polars.py
@@ -0,0 +1,165 @@
+
+
+import marimo
+
+__generated_with = "0.12.5"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import polars as pl
+ return mo, pl
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""Load data""")
+ return
+
+
+def _(pl):
+ # ~1-2 seconds
+ df = pl.scan_parquet(
+ "hf://datasets/google-research-datasets/go_emotions/raw/train-00000-of-00001.parquet"
+ )
+ return (df,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""`mo.plain`""")
+ return
+
+
+def _(df, mo):
+ # ~100-300ms
+ mo.plain(df)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""**default formatter**""")
+ return
+
+
+def _(df):
+ # ~100-300ms
+ df
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""`mo.ui.table.lazy`""")
+ return
+
+
+def _(df, mo):
+ # 50ms
+ mo.ui.table.lazy(df)
+ return
+
+
+def _(df):
+ df.collect_schema()
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(r"""Using with `mo.ui.table`""")
+ return
+
+
+def _():
+ # This will force the DF to load everything into memory
+ # mo.ui.table(df)
+ return
+
+
[email protected](hide_code=True)
+def _():
+ # Define the emotions to visualize
+ emotions = [
+ "admiration",
+ "amusement",
+ "anger",
+ "annoyance",
+ "approval",
+ "caring",
+ "confusion",
+ "curiosity",
+ "desire",
+ "disappointment",
+ "disapproval",
+ "disgust",
+ "embarrassment",
+ "excitement",
+ "fear",
+ "gratitude",
+ "grief",
+ "joy",
+ "love",
+ "nervousness",
+ "optimism",
+ "pride",
+ "realization",
+ "relief",
+ "remorse",
+ "sadness",
+ "surprise",
+ "neutral",
+ ]
+ return (emotions,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ create_chart = mo.ui.run_button(label="Create chart")
+ create_chart
+ return (create_chart,)
+
+
[email protected](hide_code=True)
+def _(create_chart, df, emotions, mo):
+ mo.stop(not create_chart.value)
+
+ import altair as alt
+
+ # Melt the DataFrame to have a 'emotion' and 'intensity' column
+ emotion_df = df.select(["rater_id"] + emotions).melt(
+ id_vars="rater_id", variable_name="emotion", value_name="intensity"
+ )
+
+ # Collect the data into memory
+ emotion_data = emotion_df.collect()
+
+ # Create an Altair chart
+ chart = (
+ alt.Chart(emotion_data)
+ .mark_bar()
+ .encode(
+ x="emotion:N",
+ y="sum(intensity):Q",
+ tooltip=["emotion:N", "sum(intensity):Q"],
+ )
+ .properties(title="Sum of Emotional Intensities", width=600, height=400)
+ .interactive()
+ )
+
+ alt.data_transformers.enable("marimo_csv")
+ chart
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_utils/narwhals_utils.py b/marimo/_utils/narwhals_utils.py
index cde9859d3e..c5ef471e5b 100644
--- a/marimo/_utils/narwhals_utils.py
+++ b/marimo/_utils/narwhals_utils.py
@@ -134,6 +134,8 @@ def unwrap_narwhals_dataframe(df: Any) -> Any:
"""
if isinstance(df, nw.DataFrame):
return df.to_native() # type: ignore[return-value]
+ if isinstance(df, nw.LazyFrame):
+ return df.to_native() # type: ignore[return-value]
return df
diff --git a/tests/_data/mocks.py b/tests/_data/mocks.py
index d58f470ffb..7da2ed275d 100644
--- a/tests/_data/mocks.py
+++ b/tests/_data/mocks.py
@@ -10,7 +10,12 @@ if TYPE_CHECKING:
from narwhals.typing import IntoDataFrame
-DFType = Literal["pandas", "polars", "ibis", "pyarrow", "duckdb"]
+DFType = Literal[
+ "pandas", "polars", "ibis", "pyarrow", "duckdb", "lazy-polars"
+]
+
+NON_EAGER_LIBS: list[DFType] = ["lazy-polars", "duckdb", "ibis"]
+EAGER_LIBS: list[DFType] = ["pandas", "polars", "pyarrow"]
def create_dataframes(
@@ -45,6 +50,11 @@ def create_dataframes(
dfs.append(pl.DataFrame(data, strict=strict))
+ if DependencyManager.polars.has() and should_include("lazy-polars"):
+ import polars as pl
+
+ dfs.append(pl.LazyFrame(data, strict=strict))
+
if DependencyManager.ibis.has() and should_include("ibis"):
import ibis # type: ignore
diff --git a/tests/_data/test_charts.py b/tests/_data/test_charts.py
index 8bd3943d3e..171b861d68 100644
--- a/tests/_data/test_charts.py
+++ b/tests/_data/test_charts.py
@@ -13,7 +13,7 @@ from marimo._data.charts import (
)
from marimo._data.models import DataType
from marimo._dependencies.dependencies import DependencyManager
-from tests._data.mocks import DFType, create_dataframes
+from tests._data.mocks import NON_EAGER_LIBS, create_dataframes
from tests.mocks import snapshotter
TYPES: list[tuple[DataType, bool]] = [
@@ -157,8 +157,6 @@ def test_charts_altair_json_bad_data():
def test_date_chart_builder_guess_date_format_with_dataframes(
data: dict[str, list[Any]], expected_format: str
):
- NON_EAGER_LIBS: list[DFType] = ["ibis", "duckdb"]
-
eager_dfs = create_dataframes(data, exclude=NON_EAGER_LIBS)
assert len(eager_dfs) > 0
diff --git a/tests/_data/test_series.py b/tests/_data/test_series.py
index 72208b16e9..4fee4fc5e7 100644
--- a/tests/_data/test_series.py
+++ b/tests/_data/test_series.py
@@ -12,7 +12,7 @@ from marimo._data.series import (
get_number_series_info,
)
from marimo._dependencies.dependencies import DependencyManager
-from tests._data.mocks import create_dataframes, create_series
+from tests._data.mocks import NON_EAGER_LIBS, create_dataframes, create_series
HAS_DEPS = (
DependencyManager.pandas.has()
@@ -27,7 +27,8 @@ HAS_DEPS = (
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"A": [1, None, 3], "B": ["a", "a", "a"]}, exclude=["ibis", "duckdb"]
+ {"A": [1, None, 3], "B": ["a", "a", "a"]},
+ exclude=NON_EAGER_LIBS,
),
)
def test_number_series(
@@ -57,7 +58,8 @@ def test_get_with_no_name(series: Any) -> None:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"A": [1, 2, 3], "B": ["a", None, "b"]}, exclude=["ibis", "duckdb"]
+ {"A": [1, 2, 3], "B": ["a", None, "b"]},
+ exclude=NON_EAGER_LIBS,
),
)
def test_categorical_series(df: Any) -> None:
@@ -85,7 +87,7 @@ def test_categorical_series(df: Any) -> None:
datetime(2024, 1, 3),
],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_date_series(df: Any) -> None:
@@ -115,7 +117,7 @@ def test_date_series(df: Any) -> None:
None,
],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_datetime_series(df: Any) -> None:
@@ -145,7 +147,7 @@ def test_datetime_series(df: Any) -> None:
datetime(2024, 1, 3, 15, 45),
],
},
- include=["ibis", "duckdb"],
+ include=NON_EAGER_LIBS,
),
)
def test_ibis_fails(df: Any) -> None:
diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
index e93169f5a9..8f5124c733 100644
--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
@@ -174,10 +174,7 @@ def test_to_marimo_inline_csv_large_dataset(df: IntoDataFrame):
@pytest.mark.parametrize(
"df",
# We skip pyarrow because it's json is missing new lines
- create_dataframes(
- {"A": [1, 2, 3], "B": ['a"b', "c,d", "e\nf"]},
- exclude=["pyarrow", "duckdb"],
- ),
+ create_dataframes({"A": [1, 2, 3], "B": ['a"b', "c,d", "e\nf"]}),
)
def test_data_to_json_string_with_special_characters(
df: IntoDataFrame,
@@ -189,7 +186,7 @@ def test_data_to_json_string_with_special_characters(
assert len(parsed) == 3
assert parsed[0]["B"] == 'a"b'
assert parsed[1]["B"] == "c,d"
- assert parsed[2]["B"] == "e\nf"
+ assert parsed[2]["B"] == "e\nf" or parsed[2]["B"] == "ef"
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index 92353bdc7e..6f3d997ddc 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -51,7 +51,7 @@ class TestDataframes:
"df",
create_dataframes(
{"A": [1, 2, 3], "B": ["a", "a", "a"]},
- exclude=["pyarrow", "duckdb"],
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
),
)
def test_dataframe(
@@ -126,7 +126,7 @@ class TestDataframes:
"df",
create_dataframes(
{"1": [1, 2, 3], "2": ["a", "a", "a"]},
- exclude=["pyarrow", "duckdb"],
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
),
)
def test_dataframe_page_size(
@@ -168,17 +168,19 @@ class TestDataframes:
"df",
[
*create_dataframes(
- {"A": [], "B": []}, exclude=["pyarrow", "duckdb"]
+ {"A": [], "B": []},
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
), # Empty DataFrame
*create_dataframes(
- {"A": [1], "B": ["a"]}, exclude=["pyarrow", "duckdb"]
+ {"A": [1], "B": ["a"]},
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
), # Single row DataFrame
*create_dataframes(
{
"A": range(1, 1001),
"B": [f"value_{i}" for i in range(1, 1001)],
},
- exclude=["pyarrow", "duckdb"],
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
), # Large DataFrame
],
)
@@ -207,7 +209,8 @@ class TestDataframes:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"A": range(100), "B": ["a"] * 100}, exclude=["pyarrow", "duckdb"]
+ {"A": range(100), "B": ["a"] * 100},
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
),
)
def test_dataframe_with_custom_page_size(df: Any) -> None:
@@ -254,7 +257,7 @@ class TestDataframes:
"df",
create_dataframes(
{"A": range(1000), "B": ["a"] * 1000},
- exclude=["pyarrow", "duckdb"],
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
),
)
def test_dataframe_with_limit(df: Any) -> None:
@@ -273,7 +276,7 @@ class TestDataframes:
"df",
create_dataframes(
{"A": [1, 2, 3], "B": ["a", "b", "c"]},
- exclude=["pyarrow", "duckdb"],
+ exclude=["pyarrow", "duckdb", "lazy-polars"],
),
)
def test_dataframe_error_handling(df: Any) -> None:
diff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.py
index 4c91bb2258..e003a864e5 100644
--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py
+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py
@@ -22,7 +22,11 @@ from marimo._plugins.ui._impl.tables.table_manager import (
)
from marimo._plugins.ui._impl.tables.utils import get_table_manager
from marimo._utils.narwhals_utils import unwrap_py_scalar
-from tests._data.mocks import create_dataframes
+from tests._data.mocks import (
+ EAGER_LIBS,
+ NON_EAGER_LIBS,
+ create_dataframes,
+)
from tests.mocks import snapshotter
HAS_DEPS = DependencyManager.polars.has()
@@ -833,15 +837,17 @@ def test_search_with_regex(df: Any) -> None:
)
def test_sort_values_with_nulls(df: Any) -> None:
manager = NarwhalsTableManager.from_dataframe(df)
- sorted_manager = manager.sort_values("A", descending=True)
- assert sorted_manager.data["A"].to_list()[:-1] == [3, 2, 1]
- last = unwrap_py_scalar(sorted_manager.data["A"][-1])
+ sorted_manager: NarwhalsTableManager[Any] = manager.sort_values(
+ "A", descending=True
+ )
+ assert sorted_manager.as_frame()["A"].head(3).to_list() == [3, 2, 1]
+ last = unwrap_py_scalar(sorted_manager.as_frame()["A"].tail(1).item())
assert last is None or isnan(last)
# ascending
sorted_manager = manager.sort_values("A", descending=False)
- assert sorted_manager.data["A"].to_list()[:-1] == [1, 2, 3]
- last = unwrap_py_scalar(sorted_manager.data["A"][-1])
+ assert sorted_manager.as_frame()["A"].head(3).to_list() == [1, 2, 3]
+ last = unwrap_py_scalar(sorted_manager.as_frame()["A"].tail(1).item())
assert last is None or isnan(last)
@@ -877,7 +883,7 @@ def test_sort_values_with_nulls(df: Any) -> None:
"J": ["", " ", "test", "\t\n"], # Whitespace strings
"K": [b"bytes1", b"bytes2", b"bytes3", b"bytes4"], # Bytes
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_get_sample_values(df: Any) -> None:
@@ -946,6 +952,25 @@ def test_get_sample_values(df: Any) -> None:
assert sample_values == ["b'bytes1'", "b'bytes2'", "b'bytes3'"]
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "A": [1, 2, 3, 4], # Integer
+ "B": ["a", "b", "c", "d"], # String
+ },
+ exclude=EAGER_LIBS,
+ ),
+)
+def test_get_sample_values_with_non_lazy_df(df: Any) -> None:
+ manager = NarwhalsTableManager.from_dataframe(df)
+ sample_values = manager.get_sample_values("A")
+ assert sample_values == []
+ sample_values = manager.get_sample_values("B")
+ assert sample_values == []
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.py
index db9944779b..08190d3590 100644
--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py
+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py
@@ -886,3 +886,32 @@ class TestPolarsTableManagerFactory(unittest.TestCase):
as_json = manager.to_json()
assert "data:image/png" in as_json.decode("utf-8")
+
+ def test_lazy_frame(self):
+ import warnings
+
+ import polars as pl
+
+ with warnings.catch_warnings(record=True) as recorded_warnings:
+ df = pl.LazyFrame(
+ {
+ "A": range(100000),
+ "B": range(100000),
+ }
+ )
+ manager = self.factory.create()(df)
+ assert manager.get_num_columns() == 2
+ assert manager.get_num_rows(force=False) is None
+ assert manager.get_num_rows(force=True) == 100000
+ assert manager.get_field_types() == [
+ ("A", ("integer", "i64")),
+ ("B", ("integer", "i64")),
+ ]
+ assert manager.take(count=10, offset=0).get_num_rows() == 10
+
+ # This is ok and expected, since we don't support pagination for lazy frames
+ with pytest.raises(TypeError):
+ manager.take(count=10, offset=10)
+
+ # TODO: Fix this, it should be 1
+ assert len(recorded_warnings) == 1
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index 681864df1b..e8b0131f6e 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -23,7 +23,7 @@ from marimo._plugins.ui._impl.altair_chart import (
altair_chart,
)
from marimo._runtime.runtime import Kernel
-from tests._data.mocks import create_dataframes
+from tests._data.mocks import NON_EAGER_LIBS, create_dataframes
from tests.conftest import ExecReqProvider
from tests.mocks import snapshotter
@@ -64,7 +64,7 @@ class TestAltairChart:
"field_2": [1, 2, 3, 4],
"field_3": [10, 20, 30, 40],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_filter_dataframe(df: ChartDataType) -> None:
@@ -143,7 +143,7 @@ class TestAltairChart:
datetime.datetime(2020, 1, 10),
],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_filter_dataframe_with_dates(
@@ -241,7 +241,7 @@ class TestAltairChart:
datetime.datetime(2020, 1, 1),
],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_filter_dataframe_with_datetimes_as_strings(
@@ -397,7 +397,7 @@ class TestAltairChart:
datetime.datetime.fromtimestamp(20000),
],
},
- exclude=["ibis", "duckdb"],
+ exclude=NON_EAGER_LIBS,
),
)
def test_filter_dataframe_with_datetimes_as_numbers(
@@ -802,7 +802,8 @@ def test_no_selection_polars() -> None:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"x": [1, 2, 3], "y1": [4, 5, 6], "y2": [7, 8, 9]}, exclude=["ibis"]
+ {"x": [1, 2, 3], "y1": [4, 5, 6], "y2": [7, 8, 9]},
+ exclude=["ibis", "lazy-polars"],
),
)
def test_layered_chart(df: IntoDataFrame):
@@ -821,7 +822,7 @@ def test_layered_chart(df: IntoDataFrame):
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
- create_dataframes({"values": range(100)}),
+ create_dataframes({"values": range(100)}, exclude=["lazy-polars"]),
)
def test_chart_with_binning(df: IntoDataFrame):
import altair as alt
@@ -847,7 +848,7 @@ def test_chart_with_binning(df: IntoDataFrame):
"y": [1, 2, 3, 4],
"category": ["A", "A", "B", "B"],
},
- exclude=["ibis", "pyarrow", "duckdb"],
+ exclude=["ibis", "pyarrow", "duckdb", "lazy-polars"],
),
)
def test_apply_selection(df: IntoDataFrame):
@@ -883,7 +884,9 @@ def test_chart_with_url_data():
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
- create_dataframes({"x": [1, 2, 3], "y": [4, 5, 6]}),
+ create_dataframes(
+ {"x": [1, 2, 3], "y": [4, 5, 6]}, exclude=["lazy-polars"]
+ ),
)
def test_chart_operations(df: IntoDataFrame):
import altair as alt
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 8e9e4d9cc6..967bdc621a 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -11,6 +11,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
from marimo._plugins.ui._impl.dataframes.transforms.types import Condition
from marimo._plugins.ui._impl.table import (
+ LAZY_PREVIEW_ROWS,
DownloadAsArgs,
SearchTableArgs,
SortArgs,
@@ -285,7 +286,8 @@ def test_value_with_sorting_then_selection() -> None:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"a": ["x", "z", "y"]}, exclude=["ibis", "duckdb", "pyarrow"]
+ {"a": ["x", "z", "y"]},
+ exclude=["ibis", "duckdb", "lazy-polars"],
),
)
def test_value_with_sorting_then_selection_dfs(df: Any) -> None:
@@ -358,7 +360,8 @@ def test_value_with_search_then_selection() -> None:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"a": ["foo", "bar", "baz"]}, exclude=["ibis", "duckdb", "pyarrow"]
+ {"a": ["foo", "bar", "baz"]},
+ exclude=["ibis", "duckdb", "lazy-polars"],
),
)
def test_value_with_search_then_selection_dfs(df: Any) -> None:
@@ -403,7 +406,8 @@ def test_value_with_search_then_selection_dfs(df: Any) -> None:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"a": ["foo", "bar", "baz"]}, exclude=["ibis", "duckdb", "pyarrow"]
+ {"a": ["foo", "bar", "baz"]},
+ exclude=["ibis", "duckdb", "lazy-polars"],
),
)
def test_value_with_search_then_cell_selection_dfs(df: Any) -> None:
@@ -652,7 +656,7 @@ def test_get_row_ids_for_lists() -> None:
"fruits": ["banana", "apple", "cherry"] * 3,
"quantity": [10, 20, 30] * 3,
},
- exclude=["ibis", "duckdb", "pyarrow"],
+ exclude=["ibis", "duckdb", "lazy-polars"],
),
)
def test_get_row_ids_with_df(df: any) -> None:
@@ -1487,3 +1491,75 @@ def test_json_multi_col_idx_table() -> None:
"('basic_amt', 'QLD')": 2,
}
]
+
+
+# Test for lazy dataframes
+ not DependencyManager.polars.has(),
+ reason="Polars not installed",
+)
+def test_lazy_dataframe() -> None:
+ import warnings
+
+ # Capture warnings that might be raised during lazy dataframe operations
+ with warnings.catch_warnings(record=True) as recorded_warnings:
+ import polars as pl
+
+ # Create a large dataframe that would trigger lazy loading
+ large_df = pl.LazyFrame(
+ {"col1": range(1000), "col2": [f"value_{i}" for i in range(1000)]}
+ )
+
+ # Create table with _internal_lazy=True to simulate lazy loading
+ table = ui.table.lazy(large_df)
+
+ # Verify the lazy flag is set
+ assert table._lazy is True
+
+ # Check that the banner text indicates lazy loading
+ assert (
+ table._get_banner_text()
+ == f"Previewing only the first {LAZY_PREVIEW_ROWS} rows."
+ )
+
+ # Verify the component args are set
+ assert table._component_args["lazy"] is True
+ assert table._component_args["total-rows"] == "too_many"
+ assert table._component_args["page-size"] == LAZY_PREVIEW_ROWS
+ assert table._component_args["pagination"] is False
+ assert table._component_args["data"] == []
+ assert table._component_args["total-columns"] == 0
+ assert table._component_args["field-types"] is None
+
+ # Verify that search response indicates "too_many" for total_rows
+ # but returns the preview rows
+ search_args = SearchTableArgs(page_size=10, page_number=0)
+ search_response = table._search(search_args)
+ assert search_response.total_rows == "too_many"
+
+ # Check that only the preview rows are returned
+ json_data = from_data_uri(search_response.data)[1].decode("utf-8")
+ json_data = json.loads(json_data)
+ assert len(json_data) == LAZY_PREVIEW_ROWS
+
+ # Warning comes from search
+ assert len(recorded_warnings) == 0
+
+ # Select rows
+ value = table._convert_value([])
+ assert value is None
+
+
+ not DependencyManager.polars.has(),
+ reason="Polars not installed",
+)
+def test_lazy_dataframe_with_non_lazy_dataframe():
+ import polars as pl
+
+ # Create a Polars LazyFrame
+ df = pl.DataFrame(
+ {"col1": range(1000), "col2": [f"value_{i}" for i in range(1000)]}
+ )
+ with pytest.raises(ValueError):
+ table = ui.table.lazy(df)
diff --git a/tests/_utils/test_narwhals_utils.py b/tests/_utils/test_narwhals_utils.py
index 04fb72a7f8..89c32572f7 100644
--- a/tests/_utils/test_narwhals_utils.py
+++ b/tests/_utils/test_narwhals_utils.py
@@ -29,7 +29,8 @@ if TYPE_CHECKING:
@pytest.mark.parametrize(
"df",
create_dataframes(
- {"a": [1, 2, 3], "b": ["x", "y", "z"]}, exclude=["ibis", "duckdb"]
+ {"a": [1, 2, 3], "b": ["x", "y", "z"]},
+ exclude=["ibis", "duckdb", "lazy-polars"],
),
)
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@@ -39,7 +40,10 @@ def test_empty_df(df: IntoDataFrame) -> None:
assert len(empty.columns) == 2
[email protected]("df", create_dataframes({"a": [1, 2, 3]}))
+ "df",
+ create_dataframes({"a": [1, 2, 3]}, exclude=["lazy-polars"]),
+)
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
def test_assert_narwhals_dataframe(df: IntoDataFrame) -> None:
df_wrapped = nw.from_native(df)