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: make ibis and dataframe-like tables lazy evaluate (#1589)
Myles Scolnick13da7edaf328
diff --git a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx b/frontend/src/components/editor/chrome/panels/datasources-panel.tsxindex 1f61fa5643..424428b724 100644--- a/frontend/src/components/editor/chrome/panels/datasources-panel.tsx+++ b/frontend/src/components/editor/chrome/panels/datasources-panel.tsx@@ -222,14 +222,16 @@ const DatasetTableItem: React.FC<{isExpanded: boolean;}> = ({ table, onExpand, onAddTable, isExpanded }) => {const renderRowsByColumns = () => {- if (table.num_rows == null || table.num_columns == null) {+ if (table.num_rows == null && table.num_columns == null) {return null;}+ const label = [`${table.num_rows} rows`, `${table.num_columns} columns`];+return (<div className="flex flex-row gap-2 items-center pl-6 group-hover:hidden"><span className="text-xs text-muted-foreground">- {table.num_rows} rows, {table.num_columns} columns+ {label.join(", ")}</span></div>);diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex 05b25e110e..8ca8b6a71b 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -15,35 +15,35 @@ def get_datasets_from_variables() -> List[DataTable]:tables: List[DataTable] = []for variable_name, value in variables:- table = get_data_table(value, variable_name)+ table = _get_data_table(value, variable_name)if table is not None:tables.append(table)return tables-def get_data_table(value: object, variable_name: str) -> Optional[DataTable]:- table = get_table_manager_or_none(value)- if table is not None:- try:- columns = [- DataTableColumn(name=column_name, type=column_type)- for column_name, column_type in table.get_field_types().items()- ]- return DataTable(- name=variable_name,- variable_name=variable_name,- num_rows=table.get_num_rows(),- num_columns=table.get_num_columns(),- source=f"Local ({table.type})",- columns=columns,- )- except Exception as e:- LOGGER.error(- "Failed to get table data for variable %s",- variable_name,- exc_info=e,- )+def _get_data_table(value: object, variable_name: str) -> Optional[DataTable]:+ try:+ table = get_table_manager_or_none(value)+ if table is None:return None- return None+ columns = [+ DataTableColumn(name=column_name, type=column_type)+ for column_name, column_type in table.get_field_types().items()+ ]+ return DataTable(+ name=variable_name,+ variable_name=variable_name,+ num_rows=table.get_num_rows(force=False),+ num_columns=table.get_num_columns(),+ source=f"Local ({table.type})",+ columns=columns,+ )+ except Exception as e:+ LOGGER.error(+ "Failed to get table data for variable %s",+ variable_name,+ exc_info=e,+ )+ return Nonediff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex 8afb85c78e..074598ad19 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -30,7 +30,7 @@ def get_column_preview(table = get_table_manager_or_none(item)if table is None:return None- if table.get_num_rows() == 0:+ if table.get_num_rows(force=True) == 0:return DataColumnPreview(table_name=table_name,column_name=column_name,diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.pyindex fc61c06d19..0c23d847ff 100644--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py@@ -7,6 +7,9 @@ from typing import TYPE_CHECKING, Any, Dict, Literal, TypedDict, Unionimport marimo._output.data.data as mo_datafrom marimo._output.utils import build_data_url+from marimo._plugins.ui._impl.tables.utils import (+ get_table_manager,+)if TYPE_CHECKING:import pandas as pd@@ -93,23 +96,7 @@ def _data_to_json_string(data: _DataType) -> str:def _data_to_csv_string(data: _DataType) -> str:"""Return a CSV string representation of the input data"""- import altair as alt- import pandas as pd-- if isinstance(data, pd.DataFrame):- sanitized = alt.utils.sanitize_dataframe(data)- as_str = sanitized.to_csv(index=False, na_rep="null")- assert isinstance(as_str, str)- return as_str- elif isinstance(data, dict):- if "values" not in data:- raise KeyError("values expected in data dict, but not present")- return pd.DataFrame.from_dict(data["values"]).to_csv(index=False)- else:- raise NotImplementedError(- "to_marimo_csv only works with data expressed as a DataFrame"- + " or as a dict"- )+ return get_table_manager(data).to_csv().decode("utf-8")def register_transformers() -> None:diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 77dfe71852..d19d750835 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -181,7 +181,7 @@ class table(self._unfiltered_manager = self._managerself._filtered_manager: Optional[TableManager[Any]] = None- totalRows = self._manager.get_num_rows()+ totalRows = self._manager.get_num_rows(force=True) or 0hasMore = totalRows > TableManager.DEFAULT_LIMITif hasMore:self._manager = self._manager.limit(TableManager.DEFAULT_LIMIT)diff --git a/marimo/_plugins/ui/_impl/tables/dataframe_protocol.py b/marimo/_plugins/ui/_impl/tables/dataframe_protocol.pynew file mode 100644index 0000000000..2d2bfbb38a--- /dev/null+++ b/marimo/_plugins/ui/_impl/tables/dataframe_protocol.py@@ -0,0 +1,342 @@+# Copyright 2024 Marimo. All rights reserved.++# Copied from https://github.com/data-apis/dataframe-api/blob/main/protocol/dataframe_protocol.py+# since this is not published on PyPI.++from __future__ import annotations++import enum+from abc import (+ ABC,+ abstractmethod,+)+from typing import (+ Any,+ Dict,+ Iterable,+ Optional,+ Sequence,+ Tuple,+ TypedDict,+)+++class DlpackDeviceType(enum.IntEnum):+ """Integer enum for device type codes matching DLPack."""++ CPU = 1+ CUDA = 2+ CPU_PINNED = 3+ OPENCL = 4+ VULKAN = 7+ METAL = 8+ VPI = 9+ ROCM = 10+++class DtypeKind(enum.IntEnum):+ """+ Integer enum for data types.++ Attributes+ ----------+ INT : int+ Matches to signed integer data type.+ UINT : int+ Matches to unsigned integer data type.+ FLOAT : int+ Matches to floating point data type.+ BOOL : int+ Matches to boolean data type.+ STRING : int+ Matches to string data type (UTF-8 encoded).+ DATETIME : int+ Matches to datetime data type.+ CATEGORICAL : int+ Matches to categorical data type.+ """++ INT = 0+ UINT = 1+ FLOAT = 2+ BOOL = 20+ STRING = 21 # UTF-8+ DATETIME = 22+ CATEGORICAL = 23+++Dtype = Tuple[DtypeKind, int, str, str] # see Column.dtype+++class CategoricalDescription(TypedDict):+ # whether the ordering of dictionary indices is semantically meaningful+ is_ordered: bool+ # whether a dictionary-style mapping of categorical values to other objects exists # noqa: E501+ is_dictionary: bool+ # Python-level only (e.g. ``{int: str}``).+ # None if not a dictionary-style categorical.+ categories: Optional[Column]+++class Column(ABC):+ """+ A column object, with only the methods and properties required by the+ interchange protocol defined.++ A column can contain one or more chunks. Each chunk can contain up to three+ buffers - a data buffer, a mask buffer (depending on null representation),+ and an offsets buffer (if variable-size binary; e.g., variable-length+ strings).++ TBD: there's also the "chunk" concept here, which is implicit in Arrow as+ multiple buffers per array (= column here). Semantically it may make+ sense to have both: chunks were meant for example for lazy evaluation+ of data which doesn't fit in memory, while multiple buffers per column+ could also come from doing a selection operation on a single+ contiguous buffer.++ Given these concepts, one would expect chunks to be all of the same+ size (say a 10,000 row dataframe could have 10 chunks of 1,000 rows),+ while multiple buffers could have data-dependent lengths. Not an issue+ in pandas if one column is backed by a single NumPy array, but in+ Arrow it seems possible.+ Are multiple chunks *and* multiple buffers per column necessary for+ the purposes of this interchange protocol, or must producers either+ reuse the chunk concept for this or copy the data?++ Note: this Column object can only be produced by ``__dataframe__``, so+ doesn't need its own version or ``__column__`` protocol.+ """++ @abstractmethod+ def size(self) -> int:+ """+ Size of the column, in elements.++ Corresponds to DataFrame.num_rows() if column is a single chunk;+ equal to size of this current chunk otherwise.++ Is a method rather than a property because it may cause a (potentially+ expensive) computation for some dataframe implementations.+ """+ pass++ @property+ @abstractmethod+ def offset(self) -> int:+ """+ Offset of first element.++ May be > 0 if using chunks; for example for a column with N chunks of+ equal size M (only the last chunk may be shorter),+ ``offset = n * M``, ``n = 0 .. N-1``.+ """+ pass++ @property+ @abstractmethod+ def dtype(self) -> Dtype:+ """+ Dtype description as a tuple ``(kind, bit-width, format string, endianness)``.++ Bit-width : the number of bits as an integer+ Format string : data type description format string in Apache Arrow C+ Data Interface format.+ Endianness : current only native endianness (``=``) is supported++ Notes:+ - Kind specifiers are aligned with DLPack where possible (hence the+ jump to 20, leave enough room for future extension)+ - Masks must be specified as boolean with either bit width 1 (for bit+ masks) or 8 (for byte masks).+ - Dtype width in bits was preferred over bytes+ - Endianness isn't too useful, but included now in case in the future+ we need to support non-native endianness+ - Went with Apache Arrow format strings over NumPy format strings+ because they're more complete from a dataframe perspective+ - Format strings are mostly useful for datetime specification, and+ for categoricals.+ - For categoricals, the format string describes the type of the+ categorical in the data buffer. In case of a separate encoding of+ the categorical (e.g. an integer to string mapping), this can+ be derived from ``self.describe_categorical``.+ - Data types not included: complex, Arrow-style null, binary, decimal,+ and nested (list, struct, map, union) dtypes.+ """ # noqa: E501+ pass++ @property+ @abstractmethod+ def describe_categorical(self) -> CategoricalDescription:+ """+ If the dtype is categorical, there are two options:+ - There are only values in the data buffer.+ - There is a separate non-categorical Column encoding categorical values.++ Raises TypeError if the dtype is not categorical++ Returns the dictionary with description on how to interpret the data buffer:+ - "is_ordered" : bool, whether the ordering of dictionary indices is+ semantically meaningful.+ - "is_dictionary" : bool, whether a mapping of+ categorical values to other objects exists+ - "categories" : Column representing the (implicit) mapping of indices to+ category values (e.g. an array of cat1, cat2, ...).+ None if not a dictionary-style categorical.++ TBD: are there any other in-memory representations that are needed?+ """ # noqa: E501+ pass++ @property+ @abstractmethod+ def null_count(self) -> Optional[int]:+ """+ Number of null elements, if known.++ Note: Arrow uses -1 to indicate "unknown", but None seems cleaner.+ """+ pass++ @property+ @abstractmethod+ def metadata(self) -> Dict[str, Any]:+ """+ The metadata for the column. See `DataFrame.metadata` for more details.+ """+ pass+++class DataFrame(ABC):+ """+ A data frame class, with only the methods required by the interchange+ protocol defined.++ A "data frame" represents an ordered collection of named columns.+ A column's "name" must be a unique string.+ Columns may be accessed by name or by position.++ This could be a public data frame class, or an object with the methods and+ attributes defined on this DataFrame class could be returned from the+ ``__dataframe__`` method of a public data frame class in a library adhering+ to the dataframe interchange protocol specification.+ """++ version = 0 # version of the protocol++ @abstractmethod+ def __dataframe__(+ self, nan_as_null: bool = False, allow_copy: bool = True+ ) -> "DataFrame":+ """+ Construct a new exchange object, potentially changing the parameters.++ ``nan_as_null`` is a DEPRECATED keyword that should not be used. See warning+ below.+ ``allow_copy`` is a keyword that defines whether or not the library is+ allowed to make a copy of the data. For example, copying data would be+ necessary if a library supports strided buffers, given that this protocol+ specifies contiguous buffers.++ WARNING: the ``nan_as_null`` parameter will be removed from the API protocol.+ Please avoid passing it as either a positional or keyword argument. Call this+ method using ``.__dataframe__(allow_copy=...)``.+ """ # noqa: E501+ pass++ @property+ @abstractmethod+ def metadata(self) -> Dict[str, Any]:+ """+ The metadata for the data frame, as a dictionary with string keys. The+ contents of `metadata` may be anything, they are meant for a library+ to store information that it needs to, e.g., roundtrip losslessly or+ for two implementations to share data that is not (yet) part of the+ interchange protocol specification. For avoiding collisions with other+ entries, please add name the keys with the name of the library+ followed by a period and the desired name, e.g, ``pandas.indexcol``.+ """+ pass++ @abstractmethod+ def num_columns(self) -> int:+ """+ Return the number of columns in the DataFrame.+ """+ pass++ @abstractmethod+ def num_rows(self) -> Optional[int]:+ # TODO: not happy with Optional, but need to flag it may be expensive+ # why include it if it may be None - what do we expect consumers+ # to do here?+ """+ Return the number of rows in the DataFrame, if available.+ """+ pass++ @abstractmethod+ def num_chunks(self) -> int:+ """+ Return the number of chunks the DataFrame consists of.+ """+ pass++ @abstractmethod+ def column_names(self) -> Iterable[str]:+ """+ Return an iterator yielding the column names.+ """+ pass++ @abstractmethod+ def get_column(self, i: int) -> Column:+ """+ Return the column at the indicated position.+ """+ pass++ @abstractmethod+ def get_column_by_name(self, name: str) -> Column:+ """+ Return the column whose name is the indicated name.+ """+ pass++ @abstractmethod+ def get_columns(self) -> Iterable[Column]:+ """+ Return an iterator yielding the columns.+ """+ pass++ @abstractmethod+ def select_columns(self, indices: Sequence[int]) -> "DataFrame":+ """+ Create a new DataFrame by selecting a subset of columns by index.+ """+ pass++ @abstractmethod+ def select_columns_by_name(self, names: Sequence[str]) -> "DataFrame":+ """+ Create a new DataFrame by selecting a subset of columns by name.+ """+ pass++ @abstractmethod+ def get_chunks(+ self, n_chunks: Optional[int] = None+ ) -> Iterable["DataFrame"]:+ """+ Return an iterator yielding the chunks.++ By default (None), yields the chunks that the data is stored as by the+ producer. If given, ``n_chunks`` must be a multiple of+ ``self.num_chunks()``, meaning the producer must subdivide each chunk+ before yielding it.++ Note that the producer must ensure that all columns are chunked the+ same way.+ """+ passdiff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex f50a4d32d1..a9a185dd5d 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -122,7 +122,8 @@ class DefaultTableManager(TableManager[JsonTableData]):del columnreturn ColumnSummary()- def get_num_rows(self) -> int:+ def get_num_rows(self, force: bool = True) -> int:+ del forceif isinstance(self.data, dict):return len(next(iter(self.data.values()), []))return len(self.data)diff --git a/marimo/_plugins/ui/_impl/tables/df_protocol_table.py b/marimo/_plugins/ui/_impl/tables/df_protocol_table.pynew file mode 100644index 0000000000..a0de456c0d--- /dev/null+++ b/marimo/_plugins/ui/_impl/tables/df_protocol_table.py@@ -0,0 +1,144 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import TYPE_CHECKING, Any, Optional, Union++from marimo._data.models import ColumnSummary+from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._impl.tables.dataframe_protocol import (+ Column,+ DtypeKind,+)+from marimo._plugins.ui._impl.tables.pyarrow_table import (+ PyArrowTableManagerFactory,+)+from marimo._plugins.ui._impl.tables.table_manager import (+ FieldType,+ FieldTypes,+ TableManager,+)+from marimo._plugins.ui._impl.tables.types import DataFrameLike++if TYPE_CHECKING:+ import pyarrow as pa # type: ignore+++class DataFrameProtocolTableManager(TableManager[DataFrameLike]):+ type = "dataframe-like"++ def __init__(self, data: DataFrameLike):+ self.data = data+ self._df = data.__dataframe__()+ self._delegate: Optional[+ TableManager[Union[pa.Table, pa.RecordBatch]]+ ] = None++ def _ensure_delegate(+ self,+ ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:+ DependencyManager.require_pyarrow(+ "for table support using the dataframe protocol"+ )++ if self._delegate is None:+ self._delegate = PyArrowTableManagerFactory.create()(+ arrow_table_from_dataframe_protocol(self.data)+ )+ return self._delegate++ def to_csv(self) -> bytes:+ return self._ensure_delegate().to_csv()++ def to_json(self) -> bytes:+ return self._ensure_delegate().to_json()++ @staticmethod+ def is_type(value: Any) -> bool:+ return isinstance(value, DataFrameLike)++ def select_rows(+ self, indices: list[int]+ ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:+ return self._ensure_delegate().select_rows(indices)++ def select_columns(+ self, columns: list[str]+ ) -> TableManager[Union[pa.Table, pa.RecordBatch]]:+ return self._ensure_delegate().select_columns(columns)++ def get_row_headers(+ self,+ ) -> list[tuple[str, list[str | int | float]]]:+ return []++ def get_field_types(self) -> FieldTypes:+ return {+ column: self._get_field_type(self._df.get_column_by_name(column))+ for column in self._df.column_names()+ }++ def limit(self, num: int) -> TableManager[Union[pa.Table, pa.RecordBatch]]:+ return self._ensure_delegate().limit(num)++ def get_summary(self, column: str) -> ColumnSummary:+ return self._ensure_delegate().get_summary(column)++ def get_num_rows(self, force: bool = True) -> Optional[int]:+ if force:+ return self._df.num_rows() or int("nan")+ return None++ def get_num_columns(self) -> int:+ return self._df.num_columns() or int("nan")++ def get_column_names(self) -> list[str]:+ return list(self._df.column_names())++ @staticmethod+ def _get_field_type(column: Column) -> FieldType:+ kind = column.dtype[0]+ if kind == DtypeKind.BOOL:+ return "boolean"+ elif kind == DtypeKind.INT:+ return "integer"+ elif kind == DtypeKind.UINT:+ return "integer"+ elif kind == DtypeKind.FLOAT:+ return "number"+ elif kind == DtypeKind.STRING:+ return "string"+ elif kind == DtypeKind.DATETIME:+ return "date"+ elif kind == DtypeKind.CATEGORICAL:+ return "string"+ else:+ return "unknown"+++# Copied from Altair+# https://github.com/vega/altair/blob/18a2c3c237014591d172284560546a2f0ac1a883/altair/utils/data.py#L343+def arrow_table_from_dataframe_protocol(+ dfi_df: DataFrameLike,+) -> "pa.lib.Table":+ """+ Convert a DataFrame Interchange Protocol compatible object+ to an Arrow Table+ """+ import pyarrow as pa+ import pyarrow.interchange as pi++ # First check if the dataframe object has a method to convert to arrow.+ # Give this preference over the pyarrow from_dataframe function+ # since the object+ # has more control over the conversion, and may have broader compatibility.+ # This is the case for Polars, which supports Date32 columns in+ # direct conversion+ # while pyarrow does not yet support this type in from_dataframe+ for convert_method_name in ("arrow", "to_arrow", "to_arrow_table"):+ convert_method = getattr(dfi_df, convert_method_name, None)+ if callable(convert_method):+ result = convert_method()+ if isinstance(result, pa.Table):+ return result++ return pi.from_dataframe(dfi_df) # type: ignore[no-any-return]diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex f413df6851..ad35f2ef52 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -215,7 +215,8 @@ class PandasTableManagerFactory(TableManagerFactory):p95=col.quantile(0.95),)- def get_num_rows(self) -> int:+ def get_num_rows(self, force: bool = True) -> int:+ del forcereturn self.data.shape[0]def get_num_columns(self) -> int:diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 44671599e6..2478cf2a0c 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -109,7 +109,8 @@ class PolarsTableManagerFactory(TableManagerFactory):p95=col.quantile(0.95),)- def get_num_rows(self) -> int:+ def get_num_rows(self, force: bool = True) -> int:+ del forcereturn self.data.heightdef get_num_columns(self) -> int:diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.pyindex d61cbb6d63..4cba4fc48a 100644--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py@@ -144,7 +144,8 @@ class PyArrowTableManagerFactory(TableManagerFactory):)return ColumnSummary()- def get_num_rows(self) -> int:+ def get_num_rows(self, force: bool = True) -> int:+ del forcereturn self.data.num_rowsdef get_num_columns(self) -> int:diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 8b83c9d0a5..3627c5875f 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -2,7 +2,7 @@from __future__ import annotationsimport abc-from typing import Any, Dict, Generic, TypeVar+from typing import Any, Dict, Generic, Optional, TypeVarimport marimo._output.data.data as mo_datafrom marimo._data.models import ColumnSummary, DataType@@ -49,11 +49,11 @@ class TableManager(abc.ABC, Generic[T]):raise NotImplementedError@abc.abstractmethod- def select_rows(self, indices: list[int]) -> TableManager[T]:+ def select_rows(self, indices: list[int]) -> TableManager[Any]:raise NotImplementedError@abc.abstractmethod- def select_columns(self, columns: list[str]) -> TableManager[T]:+ def select_columns(self, columns: list[str]) -> TableManager[Any]:raise NotImplementedError@abc.abstractmethod@@ -66,7 +66,7 @@ class TableManager(abc.ABC, Generic[T]):return {}@abc.abstractmethod- def limit(self, num: int) -> TableManager[T]:+ def limit(self, num: int) -> TableManager[Any]:raise NotImplementedError@staticmethod@@ -79,7 +79,9 @@ class TableManager(abc.ABC, Generic[T]):raise NotImplementedError@abc.abstractmethod- def get_num_rows(self) -> int:+ def get_num_rows(self, force: bool = True) -> Optional[int]:+ # This can be expensive to compute,+ # so we allow optionalsraise NotImplementedError@abc.abstractmethoddiff --git a/marimo/_plugins/ui/_impl/tables/types.py b/marimo/_plugins/ui/_impl/tables/types.pyindex dc297f9683..787d089498 100644--- a/marimo/_plugins/ui/_impl/tables/types.py+++ b/marimo/_plugins/ui/_impl/tables/types.py@@ -1,11 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Any, Protocol, runtime_checkable+from typing import Protocol, runtime_checkable++from marimo._plugins.ui._impl.tables.dataframe_protocol import DataFrame@runtime_checkableclass DataFrameLike(Protocol):def __dataframe__(self, nan_as_null: bool = False, allow_copy: bool = True- ) -> Any: ...+ ) -> DataFrame: ...diff --git a/marimo/_plugins/ui/_impl/tables/utils.py b/marimo/_plugins/ui/_impl/tables/utils.pyindex 84b0913379..58f9f58237 100644--- a/marimo/_plugins/ui/_impl/tables/utils.py+++ b/marimo/_plugins/ui/_impl/tables/utils.py@@ -1,10 +1,13 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import TYPE_CHECKING, Any, List+from typing import Any, Listfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.ui._impl.tables.default_table import DefaultTableManager+from marimo._plugins.ui._impl.tables.df_protocol_table import (+ DataFrameProtocolTableManager,+)from marimo._plugins.ui._impl.tables.pandas_table import (PandasTableManagerFactory,)@@ -20,9 +23,6 @@ from marimo._plugins.ui._impl.tables.table_manager import ()from marimo._plugins.ui._impl.tables.types import DataFrameLike-if TYPE_CHECKING:- import pyarrow-MANAGERS: List[TableManagerFactory] = [PandasTableManagerFactory(),PolarsTableManagerFactory(),@@ -45,42 +45,8 @@ def get_table_manager_or_none(data: Any) -> TableManager[Any] | None:if manager.is_type(data):return manager(data)- # If we have a DataFrameLike object, try to convert it the pyarrow table+ # If we have a DataFrameLike object, use the DataFrameProtocolTableManagerif isinstance(data, DataFrameLike):- DependencyManager.require_pyarrow(- "For table support using the dataframe protocol"- )- return PyArrowTableManagerFactory.create()(- arrow_table_from_dataframe_protocol(data)- )+ return DataFrameProtocolTableManager(data)return None---# Copied from Altair-# https://github.com/vega/altair/blob/18a2c3c237014591d172284560546a2f0ac1a883/altair/utils/data.py#L343-def arrow_table_from_dataframe_protocol(- dfi_df: DataFrameLike,-) -> "pyarrow.lib.Table":- """- Convert a DataFrame Interchange Protocol compatible object- to an Arrow Table- """- import pyarrow as pa- import pyarrow.interchange as pi-- # First check if the dataframe object has a method to convert to arrow.- # Give this preference over the pyarrow from_dataframe function- # since the object- # has more control over the conversion, and may have broader compatibility.- # This is the case for Polars, which supports Date32 columns in- # direct conversion- # while pyarrow does not yet support this type in from_dataframe- for convert_method_name in ("arrow", "to_arrow", "to_arrow_table"):- convert_method = getattr(dfi_df, convert_method_name, None)- if callable(convert_method):- result = convert_method()- if isinstance(result, pa.Table):- return result-- return pi.from_dataframe(dfi_df) # type: ignore[no-any-return]diff --git a/marimo/_smoke_tests/bugs/1586.py b/marimo/_smoke_tests/bugs/1586.pynew file mode 100644index 0000000000..80104def45--- /dev/null+++ b/marimo/_smoke_tests/bugs/1586.py@@ -0,0 +1,33 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.6.17"+app = marimo.App(width="medium")+++def __():+ import time+ import ibis++ start = time.time()+ df = ibis.read_csv(+ "https://raw.githubusercontent.com/elmoallistair/datasets/main/airlines.csv"+ )+ end = time.time()+ print(f"Time to read csv: {(end - start) * 1000}ms")+ start = time.time()+ from marimo._plugins.ui._impl.tables.utils import get_table_manager_or_none++ print("Columns:", df.__dataframe__().num_columns())+ manager = get_table_manager_or_none(df)+ print("Column types:", manager.get_field_types())+ # Print rows takes much longer+ # print(df.__dataframe__().num_rows())+ end = time.time()+ print(f"Time to read from datatable: {(end - start) * 1000}ms")+ return df, end, get_table_manager_or_none, ibis, manager, start, time+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/tables/test_df_protocol.py b/tests/_plugins/ui/_impl/tables/test_df_protocol.pynew file mode 100644index 0000000000..b0f3a0471b--- /dev/null+++ b/tests/_plugins/ui/_impl/tables/test_df_protocol.py@@ -0,0 +1,164 @@+from __future__ import annotations++import datetime+import unittest+from typing import cast++import pytest++from marimo._data.models import ColumnSummary+from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.ui._impl.tables.df_protocol_table import (+ DataFrameProtocolTableManager,+)+from marimo._plugins.ui._impl.tables.types import DataFrameLike++HAS_DEPS = DependencyManager.has_pyarrow()++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+class TestDataFrameProtocolTableManager(unittest.TestCase):+ def setUp(self) -> None:+ import pyarrow as pa++ self.data = pa.table(+ { # type: ignore+ # Integer+ "A": [1, 2, 3],+ # String+ "B": ["a", "b", "c"],+ # Float+ "C": [1.0, 2.0, 3.0],+ # Boolean+ "D": [True, False, True],+ # DateTime+ "E": [+ datetime.datetime(2021, 1, 1),+ datetime.datetime(2021, 1, 2),+ datetime.datetime(2021, 1, 3),+ ],+ }+ )+ self.manager = DataFrameProtocolTableManager(+ cast(DataFrameLike, self.data)+ )++ def test_to_csv(self) -> None:+ assert isinstance(self.manager.to_csv(), bytes)++ def test_to_json(self) -> None:+ assert isinstance(self.manager.to_json(), bytes)++ def test_select_rows(self) -> None:+ indices = [0, 2]+ selected_manager = self.manager.select_rows(indices)+ expected_data = self.data.take(indices)+ assert selected_manager.data == expected_data++ def test_select_rows_empty(self) -> None:+ selected_manager = self.manager.select_rows([])+ assert selected_manager.data.num_rows == 0++ def test_select_columns(self) -> None:+ columns = ["A"]+ selected_manager = self.manager.select_columns(columns)+ expected_data = self.data.select(columns)+ assert selected_manager.data == expected_data++ def test_get_row_headers(self) -> None:+ expected_headers = []+ assert self.manager.get_row_headers() == expected_headers++ def test_is_type(self) -> None:+ assert self.manager.is_type(self.data)+ assert not self.manager.is_type("not a dataframe")++ def test_get_field_types(self) -> None:+ import pyarrow as pa++ expected_field_types = {+ "A": "integer",+ "B": "string",+ "C": "number",+ "D": "boolean",+ "E": "date",+ }+ assert self.manager.get_field_types() == expected_field_types++ complex_data = pa.table(+ {+ "A": [1, 2, 3],+ "B": ["a", "b", "c"],+ "C": [1.0, 2.0, 3.0],+ "D": [True, False, True],+ } # type: ignore+ )+ expected_field_types = {+ "A": "integer",+ "B": "string",+ "C": "number",+ "D": "boolean",+ }+ assert (+ DataFrameProtocolTableManager(+ cast(DataFrameLike, complex_data)+ ).get_field_types()+ == expected_field_types+ )++ def test_limit(self) -> None:+ limited_manager = self.manager.limit(1)+ expected_data = self.data.take([0])+ assert limited_manager.data == expected_data++ def test_summary_integer(self) -> None:+ column = "A"+ summary = self.manager.get_summary(column)+ assert summary == ColumnSummary(+ total=3,+ nulls=0,+ unique=3,+ min=1,+ max=3,+ mean=2.0,+ )++ def test_summary_string(self) -> None:+ column = "B"+ summary = self.manager.get_summary(column)+ assert summary == ColumnSummary(+ total=3,+ nulls=0,+ unique=3,+ )++ def test_summary_number(self) -> None:+ column = "C"+ summary = self.manager.get_summary(column)+ assert summary == ColumnSummary(+ total=3,+ nulls=0,+ min=1.0,+ max=3.0,+ mean=2.0,+ )++ def test_summary_boolean(self) -> None:+ column = "D"+ summary = self.manager.get_summary(column)+ assert summary == ColumnSummary(+ total=3,+ nulls=0,+ true=2,+ false=1,+ )++ def test_summary_date(self) -> None:+ column = "E"+ summary = self.manager.get_summary(column)+ assert summary == ColumnSummary(+ total=3,+ nulls=0,+ min=datetime.datetime(2021, 1, 1, 0, 0),+ max=datetime.datetime(2021, 1, 3, 0, 0),+ )