A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: ordered field types (#2971)
Myles Scolnick700e0aa697cc
diff --git a/.github/workflows/test_be_dagger.yaml b/.github/workflows/test_be_dagger.yaml.skipsimilarity index 100%rename from .github/workflows/test_be_dagger.yamlrename to .github/workflows/test_be_dagger.yaml.skipdiff --git a/.github/workflows/test_fe_dagger.yaml b/.github/workflows/test_fe_dagger.yaml.skipsimilarity index 100%rename from .github/workflows/test_fe_dagger.yamlrename to .github/workflows/test_fe_dagger.yaml.skipdiff --git a/frontend/src/components/data-table/__test__/columns.test.tsx b/frontend/src/components/data-table/__test__/columns.test.tsxindex 4e2a475d27..b94c8b2e89 100644--- a/frontend/src/components/data-table/__test__/columns.test.tsx+++ b/frontend/src/components/data-table/__test__/columns.test.tsx@@ -49,40 +49,64 @@ test("inferFieldTypes", () => {];const fieldTypes = inferFieldTypes(data);expect(fieldTypes).toMatchInlineSnapshot(`- {- "a": [- "number",- "number",+ [+ [+ "a",+ [+ "number",+ "number",+ ],],- "b": [- "string",- "string",+ [+ "b",+ [+ "string",+ "string",+ ],],- "c": [- "unknown",- "object",+ [+ "c",+ [+ "unknown",+ "object",+ ],],- "d": [- "unknown",- "object",+ [+ "d",+ [+ "unknown",+ "object",+ ],],- "e": [- "unknown",- "object",+ [+ "e",+ [+ "unknown",+ "object",+ ],],- "f": [- "boolean",- "boolean",+ [+ "f",+ [+ "boolean",+ "boolean",+ ],],- "g": [- "boolean",- "boolean",+ [+ "g",+ [+ "boolean",+ "boolean",+ ],],- "h": [- "datetime",- "datetime",+ [+ "h",+ [+ "datetime",+ "datetime",+ ],],- }+ ]`);});@@ -90,16 +114,22 @@ test("inferFieldTypes with nulls", () => {const data = [{ a: 1, b: null }];const fieldTypes = inferFieldTypes(data);expect(fieldTypes).toMatchInlineSnapshot(`- {- "a": [- "number",- "number",+ [+ [+ "a",+ [+ "number",+ "number",+ ],],- "b": [- "unknown",- "object",+ [+ "b",+ [+ "unknown",+ "object",+ ],],- }+ ]`);});@@ -107,24 +137,30 @@ test("inferFieldTypes with mimetypes", () => {const data = [{ a: { mime: "text/csv" }, b: { mime: "image/png" } }];const fieldTypes = inferFieldTypes(data);expect(fieldTypes).toMatchInlineSnapshot(`- {- "a": [- "unknown",- "object",+ [+ [+ "a",+ [+ "unknown",+ "object",+ ],],- "b": [- "unknown",- "object",+ [+ "b",+ [+ "unknown",+ "object",+ ],],- }+ ]`);});describe("generateColumns", () => {- const fieldTypes: FieldTypesWithExternalType = {- name: ["string", "text"],- age: ["number", "integer"],- };+ const fieldTypes: FieldTypesWithExternalType = [+ ["name", ["string", "text"]],+ ["age", ["number", "integer"]],+ ];it("should generate columns with row headers", () => {const columns = generateColumns({diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex 94a2e7efcf..a6636c259f 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -17,6 +17,8 @@ import { UrlDetector } from "./url-detector";import { cn } from "@/utils/cn";import { uniformSample } from "./uniformSample";import { DatePopover } from "./date-popover";+import { Objects } from "@/utils/objects";+import { Maps } from "@/utils/maps";function inferDataType(value: unknown): [type: DataType, displayType: string] {if (typeof value === "string") {@@ -40,15 +42,15 @@ function inferDataType(value: unknown): [type: DataType, displayType: string] {export function inferFieldTypes<T>(items: T[]): FieldTypesWithExternalType {// No itemsif (items.length === 0) {- return {};+ return [];}// Not an objectif (typeof items[0] !== "object") {- return {};+ return [];}- const fieldTypes: FieldTypesWithExternalType = {};+ const fieldTypes: Record<string, [DataType, string]> = {};// This can be slow for large datasets,// so only sample 10 evenly distributed rows@@ -73,7 +75,7 @@ export function inferFieldTypes<T>(items: T[]): FieldTypesWithExternalType {});});- return fieldTypes;+ return Objects.entries(fieldTypes);}export const NAMELESS_COLUMN_PREFIX = "__m_column__";@@ -95,8 +97,10 @@ export function generateColumns<T>({}): Array<ColumnDef<T>> {const rowHeadersSet = new Set(rowHeaders);+ const typesByColumn = Maps.keyBy(fieldTypes, (entry) => entry[0]);+const getMeta = (key: string) => {- const types = fieldTypes[key];+ const types = typesByColumn.get(key)?.[1];const isRowHeader = rowHeadersSet.has(key);if (isRowHeader || !types) {@@ -113,7 +117,10 @@ export function generateColumns<T>({};};- const columnKeys = [...rowHeaders, ...Object.keys(fieldTypes)];+ const columnKeys = [+ ...rowHeaders,+ ...fieldTypes.map(([columnName]) => columnName),+ ];const columns = columnKeys.map((key, idx): ColumnDef<T> => ({id: key || `${NAMELESS_COLUMN_PREFIX}${idx}`,diff --git a/frontend/src/components/data-table/types.ts b/frontend/src/components/data-table/types.tsindex 8bc9e71d51..7bbd07c3b4 100644--- a/frontend/src/components/data-table/types.ts+++ b/frontend/src/components/data-table/types.ts@@ -1,6 +1,7 @@/* Copyright 2024 Marimo. All rights reserved. */import type { DataType } from "@/core/kernel/messages";+import { Objects } from "@/utils/objects";export interface ColumnHeaderSummary {column: string | number;@@ -12,10 +13,19 @@ export interface ColumnHeaderSummary {false?: number | null;}-export type FieldTypesWithExternalType = Record<- string,- [DataType, externalType: string]+export type FieldTypesWithExternalType = Array<+ [columnName: string, [dataType: DataType, externalType: string]]>;export type FieldTypes = Record<string, DataType>;+export function toFieldTypes(+ fieldTypes: FieldTypesWithExternalType,+): FieldTypes {+ return Objects.collect(+ fieldTypes,+ ([columnName]) => columnName,+ ([, [type]]) => type,+ );+}+export const SELECT_COLUMN_ID = "__select__";diff --git a/frontend/src/plugins/impl/DataEditorPlugin.tsx b/frontend/src/plugins/impl/DataEditorPlugin.tsxindex 4fe73fd9b1..e2fbb1decb 100644--- a/frontend/src/plugins/impl/DataEditorPlugin.tsx+++ b/frontend/src/plugins/impl/DataEditorPlugin.tsx@@ -4,7 +4,6 @@ import { createPlugin } from "../core/builder";import { TooltipProvider } from "@radix-ui/react-tooltip";import type { DataEditorProps } from "./data-editor/data-editor";import { useAsyncData } from "@/hooks/useAsyncData";-import { Objects } from "@/utils/objects";import { vegaLoadData } from "./vega/loader";import { getVegaFieldTypes } from "./vega/utils";import type { Setter } from "../types";@@ -16,6 +15,7 @@ import "./data-editor/grid.css";import "ag-grid-community/styles/ag-grid.css";import "ag-grid-community/styles/ag-theme-quartz.css";import { DATA_TYPES } from "@/core/kernel/messages";+import { toFieldTypes } from "@/components/data-table/types";type CsvURL = string;type TableData<T> = T[] | CsvURL;@@ -47,7 +47,9 @@ export const DataEditorPlugin = createPlugin<Edits>("marimo-data-editor")data: z.union([z.string(), z.array(z.object({}).passthrough())]),pagination: z.boolean().default(false),pageSize: z.number().default(10),- fieldTypes: z.record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullish(),+ fieldTypes: z+ .array(z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]))+ .nullish(),}),).withFunctions({})@@ -81,11 +83,7 @@ const LoadingDataEditor = (props: Props) => {return props.data;}- const withoutExternalTypes = Objects.mapValues(- props.fieldTypes ?? {},- ([type]) => type,- );-+ const withoutExternalTypes = toFieldTypes(props.fieldTypes ?? []);// Otherwise, load the data from the URLreturn await vegaLoadData(props.data,diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex db4adebd89..4585b19589 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -17,9 +17,10 @@ import { ColumnChartSpecModel } from "@/components/data-table/chart-spec-model";import { ColumnChartContext } from "@/components/data-table/column-summary";import { Logger } from "@/utils/Logger";-import type {- ColumnHeaderSummary,- FieldTypesWithExternalType,+import {+ toFieldTypes,+ type ColumnHeaderSummary,+ type FieldTypesWithExternalType,} from "@/components/data-table/types";import type {ColumnFiltersState,@@ -35,7 +36,6 @@ import {type ColumnFilterValue,filterToFilterCondition,} from "@/components/data-table/filters";-import { Objects } from "@/utils/objects";import React from "react";import { TooltipProvider } from "@radix-ui/react-tooltip";import { Arrays } from "@/utils/arrays";@@ -118,7 +118,9 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").record(z.enum(["left", "center", "right"])).optional(),wrappedColumns: z.array(z.string()).optional(),- fieldTypes: z.record(z.tuple([z.enum(DATA_TYPES), z.string()])).nullish(),+ fieldTypes: z+ .array(z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]))+ .nullish(),}),).withFunctions<Functions>({@@ -309,10 +311,7 @@ export const LoadingDataTableComponent = memo(};}- const withoutExternalTypes = Objects.mapValues(- props.fieldTypes ?? {},- ([type]) => type,- );+ const withoutExternalTypes = toFieldTypes(props.fieldTypes ?? []);// Otherwise, load the data from the URLtableData = await vegaLoadData(@@ -451,10 +450,7 @@ const DataTableComponent = ({if (!fieldTypes || !columnSummaries.summaries) {return ColumnChartSpecModel.EMPTY;}- const fieldTypesWithoutExternalTypes = Objects.mapValues(- fieldTypes,- ([type]) => type,- );+ const fieldTypesWithoutExternalTypes = toFieldTypes(fieldTypes);return new ColumnChartSpecModel(columnSummaries.data || [],fieldTypesWithoutExternalTypes,diff --git a/frontend/src/plugins/impl/data-editor/data-editor.tsx b/frontend/src/plugins/impl/data-editor/data-editor.tsxindex 0b4f4d8a91..f3c4f03a9c 100644--- a/frontend/src/plugins/impl/data-editor/data-editor.tsx+++ b/frontend/src/plugins/impl/data-editor/data-editor.tsx@@ -71,8 +71,11 @@ const DataEditor: React.FC<DataEditorProps<object>> = ({const { theme } = useTheme();const gridRef = useRef<AgGridReact>(null);const headerKeys = useMemo(() => {+ if (fieldTypes) {+ return fieldTypes.map(([columnName]) => columnName);+ }return getHeaderKeys(data);- }, [data]);+ }, [data, fieldTypes]);const finalRowData = useMemo(() => {for (const edit of edits) {@@ -98,12 +101,15 @@ const DataEditor: React.FC<DataEditorProps<object>> = ({filter: false,cellEditorSelector: (params) => {const colId = params.column.getColId();- const dataType = fieldTypes?.[colId];+ const dataType: DataType =+ fieldTypes?.find(+ ([columnName]) => columnName === colId,+ )?.[1]?.[0] || "string";if (dataType) {if (typeof params.value === "string" && params.value.length > 60) {return { component: "agLargeTextCellEditor", popup: true };}- return { component: cellEditorForDataType(dataType[0]) };+ return { component: cellEditorForDataType(dataType) };}return;},@@ -144,7 +150,9 @@ const DataEditor: React.FC<DataEditorProps<object>> = ({const handleAddRow = useCallback(() => {const newRow = Object.fromEntries(headerKeys.map((key) => {- const dataType = fieldTypes?.[key]?.[0] || "string";+ const dataType: DataType =+ fieldTypes?.find(([columnName]) => columnName === key)?.[1]?.[0] ||+ "string";switch (dataType) {case "boolean":return [key, false];diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex d4cdc243f4..d33e057828 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -96,9 +96,9 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")url: z.string(),total_rows: z.number(),row_headers: z.array(z.string()),- field_types: z- .record(z.tuple([z.enum(DATA_TYPES), z.string()]))- .nullable(),+ field_types: z.array(+ z.tuple([z.string(), z.tuple([z.enum(DATA_TYPES), z.string()])]),+ ),python_code: z.string().nullish(),sql_code: z.string().nullish(),}),diff --git a/frontend/src/utils/maps.ts b/frontend/src/utils/maps.tsindex 2978e4980e..8b70224f6c 100644--- a/frontend/src/utils/maps.ts+++ b/frontend/src/utils/maps.ts@@ -30,6 +30,16 @@ export const Maps = {return map;},+ collect<T, V, K = string>(+ items: Iterable<T>,+ key: (item: NoInfer<T>) => K,+ mapper: (item: NoInfer<T>) => V,+ ): Map<K, V> {+ return Maps.mapValues(Maps.keyBy(items, key), mapper);+ },+ /**+ * Filter a map by a predicate.+ */filterMap<K, V>(map: Map<K, V>,predicate: (value: V, key: K) => boolean,diff --git a/frontend/src/utils/objects.ts b/frontend/src/utils/objects.tsindex dae9cba177..e388377153 100644--- a/frontend/src/utils/objects.ts+++ b/frontend/src/utils/objects.ts@@ -49,6 +49,16 @@ export const Objects = {}return result;},+ /**+ * Collect+ */+ collect<T, V, K extends string | number = string>(+ items: T[],+ key: (item: NoInfer<T>) => K,+ mapper: (item: NoInfer<T>) => V,+ ): Record<K, V> {+ return Objects.mapValues(Objects.keyBy(items, key), mapper);+ },/*** Type-safe groupBy*/diff --git a/marimo/_data/get_datasets.py b/marimo/_data/get_datasets.pyindex 7357cb8290..2241a6e47c 100644--- a/marimo/_data/get_datasets.py+++ b/marimo/_data/get_datasets.py@@ -34,7 +34,7 @@ def _get_data_table(value: object, variable_name: str) -> Optional[DataTable]:type=column_type[0],external_type=column_type[1],)- for column_name, column_type in table.get_field_types().items()+ for column_name, column_type in table.get_field_types()]return DataTable(name=variable_name,diff --git a/marimo/_data/preview_column.py b/marimo/_data/preview_column.pyindex ebebaa3cbb..25bd689eac 100644--- a/marimo/_data/preview_column.py+++ b/marimo/_data/preview_column.py@@ -172,9 +172,7 @@ def _get_altair_chart(MaxRowsError,)- (column_type, _external_type) = table.get_field_types()[- request.column_name- ]+ (column_type, _external_type) = table.get_field_type(request.column_name)if summary.total == 0:return None, None, Falsediff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex 425178ec87..93653634e2 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -175,7 +175,7 @@ class dataframe(UIElement[Dict[str, Any], DataFrameType]):def _get_column_types(self) -> List[List[Union[str, int]]]:return [[name, dtype[0], dtype[1]]- for name, dtype in self._manager.get_field_types().items()+ for name, dtype in self._manager.get_field_types()]def get_dataframe(self, _args: EmptyArgs) -> GetDataFrameResponse:diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex e3e8222603..000fed8e5f 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -7,11 +7,12 @@ from typing import (List,Optional,Sequence,+ Tuple,Union,cast,)-from marimo._data.models import ColumnSummary+from marimo._data.models import ColumnSummary, ExternalDataTypefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._output.mime import MIMEfrom marimo._plugins.core.web_component import JSONType@@ -28,6 +29,8 @@ from marimo._plugins.ui._impl.tables.polars_table import ()from marimo._plugins.ui._impl.tables.table_manager import (ColumnName,+ FieldType,+ FieldTypes,TableManager,)@@ -189,6 +192,17 @@ class DefaultTableManager(TableManager[JsonTableData]):def get_row_headers(self) -> list[str]:return []+ def get_field_type(+ self, column_name: str+ ) -> Tuple[FieldType, ExternalDataType]:+ del column_name+ return ("unknown", "object")++ # By default, don't provide any field types+ # so the frontend can infer them+ def get_field_types(self) -> FieldTypes:+ return []+def _as_table_manager(self) -> TableManager[Any]:if DependencyManager.pandas.has():import pandas as pddiff --git a/marimo/_plugins/ui/_impl/tables/ibis_table.py b/marimo/_plugins/ui/_impl/tables/ibis_table.pyindex 00c64f21df..64c9e7e7c1 100644--- a/marimo/_plugins/ui/_impl/tables/ibis_table.py+++ b/marimo/_plugins/ui/_impl/tables/ibis_table.py@@ -20,7 +20,6 @@ from marimo._plugins.ui._impl.tables.polars_table import (from marimo._plugins.ui._impl.tables.table_manager import (ColumnName,FieldType,- FieldTypes,TableManager,TableManagerFactory,)@@ -82,12 +81,6 @@ class IbisTableManagerFactory(TableManagerFactory):def is_type(value: Any) -> bool:return isinstance(value, ibis.Table)- def get_field_types(self) -> FieldTypes:- return {- column: IbisTableManager._get_field_type(self.data[column])- for column in self.data.columns- }-def take(self, count: int, offset: int) -> IbisTableManager:if count < 0:raise ValueError("Count must be a positive integer")@@ -177,10 +170,10 @@ class IbisTableManagerFactory(TableManagerFactory):)return IbisTableManager(sorted_data)- @staticmethod- def _get_field_type(- column: ibis.expr.types.Column,+ def get_field_type(+ self, column_name: str) -> Tuple[FieldType, ExternalDataType]:+ column = self.data[column_name]dtype = column.type()if dtype.is_string():return ("string", str(dtype))diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex e88d42f0f6..b3d8e75b65 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -2,19 +2,19 @@from __future__ import annotationsimport json-from typing import Any, Optional, Union, cast+from typing import Any, Optional, Tuple, Union, castimport narwhals.stable.v1 as nwfrom narwhals.typing import IntoFrameT-from marimo._data.models import ColumnSummary+from marimo._data.models import ColumnSummary, ExternalDataTypefrom marimo._plugins.ui._impl.tables.format import (FormatMapping,format_value,)from marimo._plugins.ui._impl.tables.table_manager import (ColumnName,- FieldTypes,+ FieldType,TableManager,)from marimo._utils.narwhals_utils import (@@ -101,24 +101,23 @@ class NarwhalsTableManager(def is_type(value: Any) -> bool:return can_narwhalify(value)- def get_field_types(self) -> FieldTypes:- field_types: FieldTypes = {}- for column, dtype in self.data.schema.items():- dtype_string = str(dtype)- if is_narwhals_string_type(dtype):- field_types[column] = ("string", dtype_string)- elif dtype == nw.Boolean:- field_types[column] = ("boolean", dtype_string)- elif is_narwhals_integer_type(dtype):- field_types[column] = ("integer", dtype_string)- elif is_narwhals_temporal_type(dtype):- field_types[column] = ("date", dtype_string)- elif dtype.is_numeric():- field_types[column] = ("number", dtype_string)- else:- field_types[column] = ("unknown", dtype_string)-- return field_types+ def get_field_type(+ self, column_name: str+ ) -> Tuple[FieldType, ExternalDataType]:+ dtype = self.data.schema[column_name]+ dtype_string = str(dtype)+ if is_narwhals_string_type(dtype):+ return ("string", dtype_string)+ elif dtype == nw.Boolean:+ return ("boolean", dtype_string)+ elif is_narwhals_integer_type(dtype):+ return ("integer", dtype_string)+ elif is_narwhals_temporal_type(dtype):+ return ("date", dtype_string)+ elif dtype.is_numeric():+ return ("number", dtype_string)+ else:+ return ("unknown", dtype_string)def take(self, count: int, offset: int) -> TableManager[Any]:if count < 0:diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 5bc3a235eb..9f523af756 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -13,7 +13,6 @@ from marimo._plugins.ui._impl.tables.format import (from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManagerfrom marimo._plugins.ui._impl.tables.table_manager import (FieldType,- FieldTypes,TableManager,TableManagerFactory,)@@ -112,17 +111,11 @@ class PandasTableManagerFactory(TableManagerFactory):# We override the default implementation to use pandas's# internal fields since they get displayed in the UI.- def get_field_types(self) -> FieldTypes:- data = self.as_pandas_frame()- return {- column: PandasTableManager._get_field_type(data[column])- for column in data.columns- }-- @staticmethod- def _get_field_type(- series: pd.Series[Any] | pd.DataFrame,+ def get_field_type(+ self, column_name: str) -> Tuple[FieldType, ExternalDataType]:+ data = self.as_pandas_frame()+ series = data[column_name]# If a df has duplicate columns, it won't be a series, but# a dataframe. In this case, we take the dtype of the columnsif isinstance(series, pd.DataFrame):diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 54fd4fa885..43bc773511 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -15,7 +15,6 @@ from marimo._plugins.ui._impl.tables.format import (from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManagerfrom marimo._plugins.ui._impl.tables.table_manager import (FieldType,- FieldTypes,TableManager,TableManagerFactory,)@@ -140,16 +139,6 @@ class PolarsTableManagerFactory(TableManagerFactory):def is_type(value: Any) -> bool:return isinstance(value, pl.DataFrame)- # We override the default implementation to use polars's- # internal fields since they get displayed in the UI.- def get_field_types(self) -> FieldTypes:- return {- column: PolarsTableManager._get_field_type(dtype)- for column, dtype in self.schema().items()- }-- # We override the default implementation since- # polars supports list expressionsdef search(self, query: str) -> PolarsTableManager:query = query.lower()@@ -180,10 +169,12 @@ class PolarsTableManagerFactory(TableManagerFactory):filtered = self.as_polars_frame().filter(or_expr)return PolarsTableManager(filtered)- @staticmethod- def _get_field_type(- dtype: pl.DataType,+ # We override the default implementation to use polars's+ # internal fields since they get displayed in the UI.+ def get_field_type(+ self, column_name: str) -> Tuple[FieldType, ExternalDataType]:+ dtype = self.schema()[column_name]try:dtype_string = dtype._string_repr()except (TypeError, AttributeError):diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 577d8302c3..be19dfb28f 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport abcfrom typing import (Any,- Dict,Generic,Optional,Tuple,@@ -20,7 +19,7 @@ T = TypeVar("T")ColumnName = strFieldType = DataType-FieldTypes = Dict[ColumnName, Tuple[FieldType, ExternalDataType]]+FieldTypes = list[Tuple[ColumnName, Tuple[FieldType, ExternalDataType]]]class TableManager(abc.ABC, Generic[T]):@@ -100,10 +99,17 @@ class TableManager(abc.ABC, Generic[T]):def get_row_headers(self) -> list[str]:raise NotImplementedError+ @abc.abstractmethod+ def get_field_type(+ self, column_name: str+ ) -> Tuple[FieldType, ExternalDataType]:+ raise NotImplementedError+def get_field_types(self) -> FieldTypes:- # By default, don't provide any field types- # so the frontend can infer them- return {}+ return [+ (column_name, self.get_field_type(column_name))+ for column_name in self.get_column_names()+ ]@abc.abstractmethoddef take(self, count: int, offset: int) -> TableManager[Any]:diff --git a/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.jsonindex 289de31b20..6820765e89 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/ibis.field_types.json@@ -1,10 +1,10 @@-{- "strings": ["string", "string"],- "bool": ["boolean", "boolean"],- "int": ["integer", "int64"],- "float": ["number", "float64"],- "date": ["date", "date"],- "datetime": ["datetime", "timestamp"],- "time": ["time", "time"],- "nulls": ["string", "string"]-}+[+ ["strings", ["string", "string"]],+ ["bool", ["boolean", "boolean"]],+ ["int", ["integer", "int64"]],+ ["float", ["number", "float64"]],+ ["date", ["date", "date"]],+ ["datetime", ["datetime", "timestamp"]],+ ["time", ["time", "time"]],+ ["nulls", ["string", "string"]]+]diff --git a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.jsonindex 8c820ba3ba..191b2f97e0 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/narwhals.field_types.json@@ -1,18 +1,18 @@-{- "strings": ["string", "String"],- "bool": ["boolean", "Boolean"],- "int": ["integer", "Int64"],- "float": ["number", "Float64"],- "datetime": ["date", "Datetime(time_unit='us', time_zone=None)"],- "date": ["date", "Date"],- "struct": ["unknown", "Struct({'a': Int64, 'b': Int64})"],- "list": ["unknown", "List(Int64)"],- "array": ["unknown", "Array(Int64, 1)"],- "nulls": ["string", "String"],- "category": ["string", "Categorical"],- "set": ["unknown", "Object"],- "imaginary": ["unknown", "Object"],- "time": ["unknown", "Unknown"],- "duration": ["date", "Duration(time_unit='us')"],- "mixed_list": ["unknown", "List(String)"]-}+[+ ["strings", ["string", "String"]],+ ["bool", ["boolean", "Boolean"]],+ ["int", ["integer", "Int64"]],+ ["float", ["number", "Float64"]],+ ["datetime", ["date", "Datetime(time_unit='us', time_zone=None)"]],+ ["date", ["date", "Date"]],+ ["struct", ["unknown", "Struct({'a': Int64, 'b': Int64})"]],+ ["list", ["unknown", "List(Int64)"]],+ ["array", ["unknown", "Array(Int64, 1)"]],+ ["nulls", ["string", "String"]],+ ["category", ["string", "Categorical"]],+ ["set", ["unknown", "Object"]],+ ["imaginary", ["unknown", "Object"]],+ ["time", ["unknown", "Unknown"]],+ ["duration", ["date", "Duration(time_unit='us')"]],+ ["mixed_list", ["unknown", "List(String)"]]+]diff --git a/tests/_plugins/ui/_impl/tables/snapshots/pandas.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/pandas.field_types.jsonindex bd1883c41d..82f3bc8f4e 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/pandas.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/pandas.field_types.json@@ -1,17 +1,17 @@-{- "strings": ["string", "object"],- "bool": ["boolean", "bool"],- "int": ["integer", "int64"],- "float": ["number", "float64"],- "datetime": ["datetime", "datetime64[ns]"],- "date": ["string", "object"],- "struct": ["string", "object"],- "list": ["string", "object"],- "nulls": ["string", "object"],- "category": ["string", "category"],- "set": ["string", "object"],- "imaginary": ["unknown", "complex128"],- "time": ["string", "object"],- "duration": ["string", "timedelta64[ns]"],- "mixed_list": ["string", "object"]-}+[+ ["strings", ["string", "object"]],+ ["bool", ["boolean", "bool"]],+ ["int", ["integer", "int64"]],+ ["float", ["number", "float64"]],+ ["datetime", ["datetime", "datetime64[ns]"]],+ ["date", ["string", "object"]],+ ["struct", ["string", "object"]],+ ["list", ["string", "object"]],+ ["nulls", ["string", "object"]],+ ["category", ["string", "category"]],+ ["set", ["string", "object"]],+ ["imaginary", ["unknown", "complex128"]],+ ["time", ["string", "object"]],+ ["duration", ["string", "timedelta64[ns]"]],+ ["mixed_list", ["string", "object"]]+]diff --git a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.jsonindex 8293adf855..2998e8b431 100644--- a/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json+++ b/tests/_plugins/ui/_impl/tables/snapshots/polars.field_types.json@@ -1,18 +1,18 @@-{- "strings": ["string", "str"],- "bool": ["boolean", "bool"],- "int": ["integer", "i64"],- "float": ["number", "f64"],- "datetime": ["datetime", "datetime[\u03bcs]"],- "date": ["date", "date"],- "struct": ["unknown", "struct[2]"],- "list": ["unknown", "list[i64]"],- "array": ["unknown", "array[i64, 1]"],- "nulls": ["string", "str"],- "category": ["string", "cat"],- "set": ["unknown", "object"],- "imaginary": ["unknown", "object"],- "time": ["time", "Time"],- "duration": ["datetime", "duration[\u03bcs]"],- "mixed_list": ["unknown", "list[str]"]-}+[+ ["strings", ["string", "str"]],+ ["bool", ["boolean", "bool"]],+ ["int", ["integer", "i64"]],+ ["float", ["number", "f64"]],+ ["datetime", ["datetime", "datetime[\u03bcs]"]],+ ["date", ["date", "date"]],+ ["struct", ["unknown", "struct[2]"]],+ ["list", ["unknown", "list[i64]"]],+ ["array", ["unknown", "array[i64, 1]"]],+ ["nulls", ["string", "str"]],+ ["category", ["string", "cat"]],+ ["set", ["unknown", "object"]],+ ["imaginary", ["unknown", "object"]],+ ["time", ["time", "Time"]],+ ["duration", ["datetime", "duration[\u03bcs]"]],+ ["mixed_list", ["unknown", "list[str]"]]+]diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex 62ffd0d23b..69de213b94 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -309,7 +309,7 @@ class TestColumnarDefaultTable(unittest.TestCase):assert not self.manager.is_type("not a dataframe")def test_get_field_types(self) -> None:- assert self.manager.get_field_types() == {}+ assert self.manager.get_field_types() == []def test_limit(self) -> None:limited_manager = self.manager.take(1, 0)diff --git a/tests/_plugins/ui/_impl/tables/test_ibis_table.py b/tests/_plugins/ui/_impl/tables/test_ibis_table.pyindex 68700f6595..f121a7781a 100644--- a/tests/_plugins/ui/_impl/tables/test_ibis_table.py+++ b/tests/_plugins/ui/_impl/tables/test_ibis_table.py@@ -121,13 +121,13 @@ class TestIbisTableManagerFactory(unittest.TestCase):assert not self.manager.is_type("not a table")def test_get_field_types(self) -> None:- expected_field_types = {- "A": ("integer", "int64"),- "B": ("string", "string"),- "C": ("number", "float64"),- "D": ("boolean", "boolean"),- "E": ("datetime", "timestamp"),- }+ expected_field_types = [+ ("A", ("integer", "int64")),+ ("B", ("string", "string")),+ ("C", ("number", "float64")),+ ("D", ("boolean", "boolean")),+ ("E", ("datetime", "timestamp")),+ ]assert self.manager.get_field_types() == expected_field_typesdef test_limit(self) -> None:@@ -273,8 +273,7 @@ class TestIbisTableManagerFactory(unittest.TestCase):table = ibis.memtable({"A": [1, "two", 3.0, True]})manager = self.factory.create()(table)- field_types = manager.get_field_types()- assert field_types["A"] == ("unknown", "unknown")+ assert manager.get_field_type("A") == ("unknown", "unknown")def test_search_with_regex(self) -> None:import ibisdiff --git a/tests/_plugins/ui/_impl/tables/test_narwhals.py b/tests/_plugins/ui/_impl/tables/test_narwhals.pyindex 33413a6c97..f5e2ea7a20 100644--- a/tests/_plugins/ui/_impl/tables/test_narwhals.py+++ b/tests/_plugins/ui/_impl/tables/test_narwhals.py@@ -186,13 +186,13 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):def test_get_field_types(self) -> None:import polars as pl- expected_field_types = {- "A": ("integer", "Int64"),- "B": ("string", "String"),- "C": ("number", "Float64"),- "D": ("boolean", "Boolean"),- "E": ("date", "Datetime(time_unit='us', time_zone=None)"),- }+ expected_field_types = [+ ("A", ("integer", "Int64")),+ ("B", ("string", "String")),+ ("C", ("number", "Float64")),+ ("D", ("boolean", "Boolean")),+ ("E", ("date", "Datetime(time_unit='us', time_zone=None)")),+ ]assert self.manager.get_field_types() == expected_field_typescomplex_data = pl.DataFrame(@@ -221,18 +221,18 @@ class TestNarwhalsTableManagerFactory(unittest.TestCase):],})- expected_field_types = {- "A": ("integer", "Int64"),- "B": ("string", "String"),- "C": ("number", "Float64"),- "D": ("boolean", "Boolean"),- "E": ("unknown", "Object"),- "F": ("unknown", "Unknown"),- "G": ("unknown", "Object"),- "H": ("date", "Datetime(time_unit='us', time_zone=None)"),- "I": ("string", "String"),- "J": ("string", "String"),- }+ expected_field_types = [+ ("A", ("integer", "Int64")),+ ("B", ("string", "String")),+ ("C", ("number", "Float64")),+ ("D", ("boolean", "Boolean")),+ ("E", ("unknown", "Object")),+ ("F", ("unknown", "Unknown")),+ ("G", ("unknown", "Object")),+ ("H", ("date", "Datetime(time_unit='us', time_zone=None)")),+ ("I", ("string", "String")),+ ("J", ("string", "String")),+ ]assert (NarwhalsTableManager.from_dataframe(complex_data).get_field_types()== expected_field_types@@ -686,7 +686,7 @@ def test_empty_dataframe(df: Any) -> None:assert empty_manager.get_num_rows() == 0assert empty_manager.get_num_columns() == 0assert empty_manager.get_column_names() == []- assert empty_manager.get_field_types() == {}+ assert empty_manager.get_field_types() == []@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")@@ -712,8 +712,7 @@ def test_dataframe_with_all_null_column(df: Any) -> None:)def test_dataframe_with_mixed_types(df: Any) -> None:manager = NarwhalsTableManager.from_dataframe(df)- field_types = manager.get_field_types()- assert field_types["A"] == ("string", "String")+ assert manager.get_field_type("A") == ("string", "String")@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex d39640ae59..37bc5fab76 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -207,14 +207,14 @@ class TestPandasTableManager(unittest.TestCase):assert not self.manager.is_type("not a dataframe")def test_get_field_types(self) -> None:- expected_field_types = {- "A": ("integer", "int64"),- "B": ("string", "object"),- "C": ("number", "float64"),- "D": ("boolean", "bool"),- "E": ("datetime", "datetime64[ns]"),- "F": ("string", "object"),- }+ expected_field_types = [+ ("A", ("integer", "int64")),+ ("B", ("string", "object")),+ ("C", ("number", "float64")),+ ("D", ("boolean", "bool")),+ ("E", ("datetime", "datetime64[ns]")),+ ("F", ("string", "object")),+ ]assert self.manager.get_field_types() == expected_field_typescomplex_data = pd.DataFrame(@@ -243,18 +243,18 @@ class TestPandasTableManager(unittest.TestCase):],})- expected_field_types = {- "A": ("integer", "int64"),- "B": ("string", "object"),- "C": ("number", "float64"),- "D": ("boolean", "bool"),- "E": ("unknown", "complex128"),- "F": ("string", "object"),- "G": ("string", "object"),- "H": ("datetime", "datetime64[ns]"),- "I": ("string", "timedelta64[ns]"),- "J": ("string", "interval[int64, right]"),- }+ expected_field_types = [+ ("A", ("integer", "int64")),+ ("B", ("string", "object")),+ ("C", ("number", "float64")),+ ("D", ("boolean", "bool")),+ ("E", ("unknown", "complex128")),+ ("F", ("string", "object")),+ ("G", ("string", "object")),+ ("H", ("datetime", "datetime64[ns]")),+ ("I", ("string", "timedelta64[ns]")),+ ("J", ("string", "interval[int64, right]")),+ ]assert (self.factory.create()(complex_data).get_field_types()== expected_field_types@@ -272,9 +272,9 @@ class TestPandasTableManager(unittest.TestCase):})data = data.rename(columns={"A": "B"})- expected_field_types = {- "B": ("string", "object"),- }+ expected_field_types = [+ ("B", ("string", "object")),+ ]assert (self.factory.create()(data).get_field_types()== expected_field_types@@ -288,9 +288,9 @@ class TestPandasTableManager(unittest.TestCase):})data = data.rename(columns={"A": "B"})- expected_field_types = {- "B": ("string", "object"),- }+ expected_field_types = [+ ("B", ("string", "object")),+ ]assert (self.factory.create()(data).get_field_types()== expected_field_types@@ -304,9 +304,9 @@ class TestPandasTableManager(unittest.TestCase):})data = data.rename(columns={"A": "B"})- expected_field_types = {- "B": ("string", "object"),- }+ expected_field_types = [+ ("B", ("string", "object")),+ ]assert (self.factory.create()(data).get_field_types()== expected_field_types@@ -748,7 +748,7 @@ class TestPandasTableManager(unittest.TestCase):assert empty_manager.get_num_rows() == 0assert empty_manager.get_num_columns() == 0assert empty_manager.get_column_names() == []- assert empty_manager.get_field_types() == {}+ assert empty_manager.get_field_types() == []def test_dataframe_with_all_null_column(self) -> None:df = pd.DataFrame({"A": [1, 2, 3], "B": [None, None, None]})@@ -761,8 +761,7 @@ class TestPandasTableManager(unittest.TestCase):def test_dataframe_with_mixed_types(self) -> None:df = pd.DataFrame({"A": [1, "two", 3.0, True]})manager = self.factory.create()(df)- field_types = manager.get_field_types()- assert field_types["A"] == ("string", "object")+ assert manager.get_field_type("A") == ("string", "object")def test_search_with_regex(self) -> None:df = pd.DataFrame({"A": ["apple", "banana", "cherry"]})@@ -812,8 +811,10 @@ class TestPandasTableManager(unittest.TestCase):})manager = self.factory.create()(data)- field_types = manager.get_field_types()- assert field_types["date_col"] == ("string", "object")- assert field_types["datetime_col"] == ("datetime", "datetime64[ns]")- assert field_types["time_col"] == ("string", "object")+ assert manager.get_field_type("date_col") == ("string", "object")+ assert manager.get_field_type("datetime_col") == (+ "datetime",+ "datetime64[ns]",+ )+ assert manager.get_field_type("time_col") == ("string", "object")diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex bbac0d624c..5621ecc788 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -195,13 +195,13 @@ class TestPolarsTableManagerFactory(unittest.TestCase):def test_get_field_types(self) -> None:import polars as pl- expected_field_types = {- "A": ("integer", "i64"),- "B": ("string", "str"),- "C": ("number", "f64"),- "D": ("boolean", "bool"),- "E": ("datetime", "datetime[μs]"),- }+ expected_field_types = [+ ("A", ("integer", "i64")),+ ("B", ("string", "str")),+ ("C", ("number", "f64")),+ ("D", ("boolean", "bool")),+ ("E", ("datetime", "datetime[μs]")),+ ]assert self.manager.get_field_types() == expected_field_typescomplex_data = pl.DataFrame(@@ -240,20 +240,20 @@ class TestPolarsTableManagerFactory(unittest.TestCase):],})- expected_field_types = {- "A": ("integer", "i64"),- "B": ("string", "str"),- "C": ("number", "f64"),- "D": ("boolean", "bool"),- "E": ("unknown", "object"),- "F": ("unknown", "null"),- "G": ("unknown", "object"),- "H": ("datetime", "datetime[μs]"),- "I": ("string", "str"),- "J": ("string", "str"),- "K": ("date", "date"),- "L": ("time", "Time"),- }+ expected_field_types = [+ ("A", ("integer", "i64")),+ ("B", ("string", "str")),+ ("C", ("number", "f64")),+ ("D", ("boolean", "bool")),+ ("E", ("unknown", "object")),+ ("F", ("unknown", "null")),+ ("G", ("unknown", "object")),+ ("H", ("datetime", "datetime[μs]")),+ ("I", ("string", "str")),+ ("J", ("string", "str")),+ ("K", ("date", "date")),+ ("L", ("time", "Time")),+ ]assert (self.factory.create()(complex_data).get_field_types()== expected_field_types@@ -674,7 +674,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):assert empty_manager.get_num_rows() == 0assert empty_manager.get_num_columns() == 0assert empty_manager.get_column_names() == []- assert empty_manager.get_field_types() == {}+ assert empty_manager.get_field_types() == []def test_dataframe_with_all_null_column(self) -> None:import polars as pl@@ -690,8 +690,7 @@ class TestPolarsTableManagerFactory(unittest.TestCase):df = pl.DataFrame({"A": [1, "two", 3.0, True]}, strict=False)manager = self.factory.create()(df)- field_types = manager.get_field_types()- assert field_types["A"] == ("string", "str")+ assert manager.get_field_type("A") == ("string", "str")def test_search_with_regex(self) -> None:import polars as pl@@ -729,8 +728,10 @@ class TestPolarsTableManagerFactory(unittest.TestCase):})manager = self.factory.create()(data)- field_types = manager.get_field_types()- assert field_types["date_col"] == ("date", "date")- assert field_types["datetime_col"] == ("datetime", "datetime[μs]")- assert field_types["time_col"] == ("time", "Time")+ assert manager.get_field_type("date_col") == ("date", "date")+ assert manager.get_field_type("datetime_col") == (+ "datetime",+ "datetime[μs]",+ )+ assert manager.get_field_type("time_col") == ("time", "Time")