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.

feat: formatters for Ibis objects (#5855)

Kyrre Wahl Kongsgård2ce45a05baf5
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index 7c8b4b706f..a681da8d67 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import os
import re
+from enum import Enum
+from typing import Any
import narwhals.stable.v1 as nw
@@ -12,7 +14,9 @@ from marimo._output.formatters.formatter_factory import (
FormatterFactory,
Unregister,
)
+from marimo._plugins.stateless.json_output import json_output
from marimo._plugins.stateless.mermaid import mermaid
+from marimo._plugins.stateless.plain_text import plain_text
from marimo._plugins.ui._impl import tabs
from marimo._plugins.ui._impl.table import get_default_table_page_size, table
from marimo._runtime.patches import patch_polars_write_json
@@ -206,3 +210,209 @@ class PySparkFormatter(FormatterFactory):
@formatting.opinionated_formatter(pyspark_DataFrame)
def _show_df(df: pyspark_DataFrame) -> tuple[KnownMimeType, str]:
return table.lazy(df)._mime_()
+
+
+class IbisFormatter(FormatterFactory):
+ """Custom formatting for Ibis expressions.
+
+ Provides custom formatters for tables, columns, and scalar values.
+
+ When eager execution is enabled, tables, columns and values are executed
+ and displayed using an appropriate marimo formatter.
+ For lazy expressions, show the query representation and the SQL (if available).
+ For unbound expressions, show the query representation and the SQL.
+ """
+
+ @staticmethod
+ def package_name() -> str:
+ return "ibis"
+
+ def register(self) -> None:
+ import ibis # type: ignore[import-not-found]
+ import ibis.expr.types as ir # type: ignore[import-not-found]
+ from ibis.backends.sql import ( # type: ignore[import-not-found]
+ SQLBackend,
+ )
+
+ from marimo._output import formatting
+
+ if not include_opinionated():
+ return
+
+ class IbisDisplayMode(Enum):
+ """Display mode for Ibis expressions."""
+
+ INTERACTIVE = "interactive" # Execute and show as table
+ UNBOUND = (
+ "unbound" # Show Expression+SQL tabs (contains unbound tables)
+ )
+ LAZY = "lazy" # Show Expression+SQL tabs (non-interactive mode)
+
+ def _get_display_mode(expr: ir.Expr) -> IbisDisplayMode:
+ """Get display mode for expression.
+
+ Returns:
+ - INTERACTIVE: Execute and show as interactive table
+ - UNBOUND: Show Expression+SQL tabs (contains unbound tables)
+ - LAZY: Show Expression+SQL tabs (non-interactive mode)
+ """
+
+ # We are using _find_backends() to detect unbound expressions instead of get_backend(),
+ # because the latter throws a general IbisError rather than UnboundExpressionError
+ # https://github.com/ibis-project/ibis/blob/main/ibis/expr/types/core.py#L330.
+ #
+ # If this private method is removed in future versions, fallback to:
+ # try: expr.get_backend() except IbisError: has_unbound = True
+ _, has_unbound = expr._find_backends()
+
+ if has_unbound:
+ return IbisDisplayMode.UNBOUND
+ elif not ibis.options.interactive:
+ return IbisDisplayMode.LAZY
+ else:
+ return IbisDisplayMode.INTERACTIVE
+
+ def _render_plain_text_fallback(
+ obj: Any,
+ ) -> tuple[KnownMimeType, str]:
+ """Helper to render object as plain text with fallback."""
+ try:
+ return plain_text(repr(obj))._mime_()
+ except Exception:
+ return (
+ "text/plain",
+ f"<{type(obj).__name__} object - could not display>",
+ )
+
+ def _get_sql_repr(expr: ir.Expr, mode: IbisDisplayMode) -> str:
+ """Get SQL representation or message if backend doesn't support SQL."""
+ try:
+ if mode == IbisDisplayMode.UNBOUND or isinstance(
+ expr.get_backend(), SQLBackend
+ ):
+ return f"```sql\n{ibis.to_sql(expr)}\n```"
+ else:
+ return "Backend doesn't support SQL"
+ except Exception as e:
+ LOGGER.warning("Could not generate SQL for expression: %s", e)
+ return f"Could not generate SQL: {e}"
+
+ def _format_lazy_expression(
+ expr: ir.Expr, mode: IbisDisplayMode
+ ) -> tuple[KnownMimeType, str]:
+ """Display the expression as a lazy representation with Expression and SQL."""
+
+ # We need to call _noninteractive_repr() directly instead of just relying on ir.Expr.__repr__() because
+ # otherwise when the expression is unbound and interactive mode is enabled it will try to execute it.
+ # https://github.com/ibis-project/ibis/blob/8a7534c8ef3c675229edd17f2f4467f314d0c143/ibis/expr/types/core.py#L53C3-L58C1
+ #
+ # If this private method is removed in future versions, fallback to repr(expr) is acceptable -
+ # unbound expressions in interactive mode will crash, but that's a reasonable failure mode
+ # since users shouldn't typically have unbound expressions in interactive contexts.
+ expr_repr = expr._noninteractive_repr()
+ if mode == IbisDisplayMode.UNBOUND:
+ expr_content = (
+ f"Contains unbound tables - cannot execute\n\n{expr_repr}"
+ )
+ else:
+ expr_content = expr_repr
+
+ sql_content = _get_sql_repr(expr, mode)
+
+ return tabs.tabs(
+ {"Expression": plain_text(expr_content), "SQL": sql_content}
+ )._mime_()
+
+ def _format_ibis_expression(
+ expr: ir.Expr,
+ ) -> tuple[KnownMimeType, str]:
+ """Format Ibis expressions.
+
+ Interactive mode: Shows data as marimo table
+ Non-interactive or unbound: Shows the expression representation
+ """
+ try:
+ mode = _get_display_mode(expr)
+
+ if mode == IbisDisplayMode.INTERACTIVE:
+ return table(
+ expr, selection=None, pagination=True
+ )._mime_()
+ else:
+ return _format_lazy_expression(expr, mode)
+
+ except BaseException as e:
+ LOGGER.warning("Failed to format Ibis expression: %s", e)
+ # Simple fallback - just show the expression as text
+ return _render_plain_text_fallback(expr)
+
+ @formatting.formatter(ir.Table)
+ def _show_marimo_ibis_table(
+ table_expr: ir.Table,
+ ) -> tuple[KnownMimeType, str]:
+ """Format Table expressions.
+
+ Interactive, bound expressions show as table widgets.
+ All other cases show lazy expression representation.
+
+ Examples:
+ --------
+ >>> t.mutate(c=t.a + t.b)
+ >>> t.filter(t.species == "Adelie")
+ >>> ratings.select("userId", "rating")
+ """
+ return _format_ibis_expression(table_expr)
+
+ @formatting.formatter(ir.Column)
+ def _show_marimo_ibis_column(
+ column_expr: ir.Column,
+ ) -> tuple[KnownMimeType, str]:
+ """Format Column expressions.
+
+ Columns are converted to single-column tables via .as_table()
+ then formatted using standard table logic.
+
+ Examples:
+ --------
+ >>> t.column
+ >>> t["species"]
+ >>> t.bill_length_mm
+ >>> t.body_mass_g.cast("float32")
+ """
+ return _format_ibis_expression(column_expr.as_table())
+
+ @formatting.formatter(ir.Scalar)
+ def _show_scalar(scalar: ir.Scalar) -> tuple[KnownMimeType, str]:
+ """Format Scalar expressions.
+
+ Simple scalars render as text.
+ Complex scalars (arrays, maps, structs) render using marimo's json_output.
+
+ Bound, interactive expressions execute to single values.
+ All other cases are displayed using the lazy expression representation.
+
+ Examples:
+ --------
+ >>> t.body_mass_g.max()
+ >>> t.bill_depth_mm.quantile(0.99)
+ >>> ibis.literal(42)
+ >>> t.species.nunique()
+ """
+ mode = _get_display_mode(scalar)
+
+ if mode != IbisDisplayMode.INTERACTIVE:
+ return _format_lazy_expression(scalar, mode)
+
+ # Interactive mode - try to execute
+ try:
+ val = scalar.to_pyarrow().as_py()
+ # Complex scalars as JSON, simple ones as text
+ if isinstance(
+ scalar, (ir.ArrayScalar, ir.StructScalar, ir.MapScalar)
+ ):
+ return json_output(json_data=val)._mime_()
+ else:
+ return _render_plain_text_fallback(val)
+ except BaseException as e:
+ LOGGER.warning("Failed to format Ibis scalar: %s", e)
+ return _render_plain_text_fallback(scalar)
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index dbdddd1f35..abaa4a6b53 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -17,6 +17,7 @@ from marimo._output.formatters.arviz_formatters import ArviZFormatter
from marimo._output.formatters.bokeh_formatters import BokehFormatter
from marimo._output.formatters.cell import CellFormatter
from marimo._output.formatters.df_formatters import (
+ IbisFormatter,
PolarsFormatter,
PyArrowFormatter,
PySparkFormatter,
@@ -49,6 +50,7 @@ if TYPE_CHECKING:
THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
AltairFormatter.package_name(): AltairFormatter(),
MatplotlibFormatter.package_name(): MatplotlibFormatter(),
+ IbisFormatter.package_name(): IbisFormatter(),
PandasFormatter.package_name(): PandasFormatter(),
PolarsFormatter.package_name(): PolarsFormatter(),
PyArrowFormatter.package_name(): PyArrowFormatter(),
diff --git a/marimo/_smoke_tests/ibis_formatting.py b/marimo/_smoke_tests/ibis_formatting.py
new file mode 100644
index 0000000000..b558e7e92f
--- /dev/null
+++ b/marimo/_smoke_tests/ibis_formatting.py
@@ -0,0 +1,215 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "ibis-framework[duckdb,polars]==10.8.0",
+# "marimo",
+# "polars==1.32.0",
+# ]
+# ///
+
+import marimo
+
+__generated_with = "0.14.15"
+app = marimo.App(width="medium")
+
+
+def _():
+ import ibis
+ import polars as pl
+ import marimo as mo
+ return ibis, pl
+
+
+def _():
+ from ibis import _
+ from datetime import datetime
+ return
+
+
+def _():
+ test_data = {
+ "str": ["a", "c", "hello"],
+ "num": [1, 2, 3],
+ "list": [["a", "b"], ["c"], []],
+ "struct": [{"a": 0}, {"a": 1}, {"a": 2}],
+ "floats": [1.1, 2.2, None],
+ }
+ return (test_data,)
+
+
+def _(ibis, test_data):
+ t = ibis.memtable(test_data)
+ return (t,)
+
+
+def _(ibis, t):
+ # Table - lazy mode: Expression + SQL tabs
+ ibis.options.interactive = False
+
+ t
+ return
+
+
+def _(ibis, t):
+ # Column - lazy mode: Expression + SQL tabs
+ ibis.options.interactive = False
+
+ t.struct
+ return
+
+
+def _(ibis, t):
+ # Scalar - lazy mode: Expression + SQL tabs
+ ibis.options.interactive = False
+
+ t.floats.min()
+ return
+
+
+def _(ibis, t):
+ # Table - interactive mode: table widget
+ ibis.options.interactive = True
+
+ t
+ return
+
+
+def _(ibis, t):
+ # Column - interactive mode: table widget
+ ibis.options.interactive = True
+
+ t.struct
+ return
+
+
+def _(ibis, t):
+ # Array scalar - interactive mode: JSON output
+ ibis.options.interactive = True
+
+ t.list.first()
+ return
+
+
+def _(ibis, t):
+ # Scalar - interactive mode: plain text
+ ibis.options.interactive = True
+
+ t.floats.min()
+ return
+
+
+def _(ibis):
+ # Unbound tables
+
+ t1 = ibis.table(dict(value1="float", key1="string", key2="string"), name="table1")
+ t2 = ibis.table(dict(value2="float", key3="string", key4="string"), name="table2")
+
+ joined = t1.left_join(t2, t1.key1 == t2.key3)
+ return (joined,)
+
+
+def _(ibis, joined):
+ # Unbound table: Expression + SQL tabs
+ ibis.options.interactive = False
+
+ joined
+ return
+
+
+def _(ibis, joined):
+ # Unbound table - interactive mode: Expression + SQL tabs
+ ibis.options.interactive = True
+
+ joined
+ return
+
+
+def _(pl):
+ lazy_frame = pl.LazyFrame({"name": ["Jimmy", "Keith"], "band": ["Led Zeppelin", "Stones"]})
+ return (lazy_frame,)
+
+
+def _(ibis, lazy_frame):
+ pl_connection = ibis.polars.connect(tables={"band_members": lazy_frame})
+ return (pl_connection,)
+
+
+def _(ibis, pl_connection):
+ # Polars table - lazy mode: Expression + SQL tabs (SQL shows "Backend doesn't support SQL")
+ ibis.options.interactive = False
+
+ pl_connection.table("band_members")
+ return
+
+
+def _(ibis, pl_connection):
+ # Polars scalar - lazy mode: Expression + SQL tabs (SQL shows "Backend doesn't support SQL")
+ ibis.options.interactive = False
+
+ pl_connection.table("band_members").name.first()
+ return
+
+
+def _(ibis, pl_connection):
+ # Polars table - interactive mode: table widget
+ ibis.options.interactive = True
+
+ pl_connection.table("band_members")
+ return
+
+
+def _(ibis, pl_connection):
+ # Polars scalar - interactive mode: plain text
+ ibis.options.interactive = True
+
+ pl_connection.table("band_members").name.first()
+ return
+
+
+def _(ibis, t):
+ duckb_con = ibis.duckdb.connect()
+ duckdb_table = duckb_con.create_table("test", t, overwrite=True)
+ return (duckdb_table,)
+
+
+def _(duckdb_table, ibis):
+ # DuckDB table - lazy mode: Expression + SQL tabs
+ ibis.options.interactive = False
+
+ duckdb_table
+ return
+
+
+def _(duckdb_table, ibis):
+ # DuckDB table - interactive mode: table widget
+ ibis.options.interactive = True
+
+ duckdb_table
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/formatters/test_ibis_formatters.py b/tests/_output/formatters/test_ibis_formatters.py
new file mode 100644
index 0000000000..a20be54de1
--- /dev/null
+++ b/tests/_output/formatters/test_ibis_formatters.py
@@ -0,0 +1,199 @@
+from __future__ import annotations
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._output.formatters.formatters import register_formatters
+from marimo._output.formatting import (
+ get_formatter,
+)
+
+HAS_IBIS = DependencyManager.ibis.has()
+HAS_POLARS = DependencyManager.polars.has()
+
+
+def test_table():
+ """Create a test ibis table with various data types."""
+ if not HAS_IBIS:
+ pytest.skip("ibis not available")
+
+ import ibis
+
+ test_data = {
+ "str": ["a", "c", "hello"],
+ "num": [1, 2, 3],
+ "list": [["a", "b"], ["c"], []],
+ "struct": [{"a": 0}, {"a": 1}, {"a": 2}],
+ "floats": [1.1, 2.2, None],
+ }
+ return ibis.memtable(test_data)
+
+
[email protected](not HAS_IBIS, reason="ibis not installed")
+def test_ibis_formatters_interactive_mode(test_table) -> None:
+ """Test ibis formatters in interactive mode."""
+ register_formatters()
+
+ import ibis
+
+ # Save original setting
+ original_interactive = ibis.options.interactive
+ ibis.options.interactive = True
+
+ try:
+ # Test table - should return table widget
+ formatter = get_formatter(test_table, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(test_table)
+ assert mime == "text/html"
+ assert "<marimo-table" in content
+
+ # Test column - should return table widget via as_table()
+ column = test_table.struct
+ formatter = get_formatter(column, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(column)
+ assert mime == "text/html"
+ assert "<marimo-table" in content
+
+ # Test scalar - should return formatted text
+ scalar = test_table.floats.min()
+ formatter = get_formatter(scalar, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(scalar)
+ assert mime == "text/html"
+ assert content.startswith("<pre")
+
+ finally:
+ ibis.options.interactive = original_interactive
+
+
[email protected](not HAS_IBIS, reason="ibis not installed")
+def test_ibis_formatters_lazy_mode(test_table) -> None:
+ """Test ibis formatters in lazy mode."""
+ register_formatters()
+
+ import ibis
+
+ # Save original setting
+ original_interactive = ibis.options.interactive
+ ibis.options.interactive = False
+
+ try:
+ # Test table - should return Expression+SQL tabs
+ formatter = get_formatter(test_table, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(test_table)
+ assert mime == "text/html"
+ assert "<marimo-tabs" in content
+
+ # Test column - should return Expression+SQL tabs
+ column = test_table.struct
+ formatter = get_formatter(column, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(column)
+ assert mime == "text/html"
+ assert "<marimo-tabs" in content
+
+ # Test scalar - should return Expression+SQL tabs
+ scalar = test_table.floats.min()
+ formatter = get_formatter(scalar, include_opinionated=False)
+ assert formatter is not None
+ mime, content = formatter(scalar)
+ assert mime == "text/html"
+ assert "<marimo-tabs" in content
+
+ finally:
+ ibis.options.interactive = original_interactive
+
+
[email protected](not HAS_IBIS, reason="ibis not installed")
+def test_ibis_unbound_expressions() -> None:
+ """Test unbound expressions - should always show Expression+SQL tabs."""
+ register_formatters()
+
+ import ibis
+
+ # Create unbound tables like in smoke tests
+ t1 = ibis.table(
+ dict(value1="float", key1="string", key2="string"), name="table1"
+ )
+ t2 = ibis.table(
+ dict(value2="float", key3="string", key4="string"), name="table2"
+ )
+ joined = t1.left_join(t2, t1.key1 == t2.key3)
+
+ # Test in both interactive modes - should always return tabs
+ for interactive_mode in [True, False]:
+ original_interactive = ibis.options.interactive
+ ibis.options.interactive = interactive_mode
+
+ try:
+ formatter = get_formatter(joined, include_opinionated=False)
+ assert formatter is not None
+
+ mime, content = formatter(joined)
+ assert mime == "text/html"
+ assert "<marimo-tabs" in content
+ finally:
+ ibis.options.interactive = original_interactive
+
+
[email protected](not HAS_IBIS, reason="ibis not installed")
+def test_ibis_complex_scalar_interactive(test_table) -> None:
+ """Test complex scalar (array) in interactive mode - should return JSON output."""
+ register_formatters()
+
+ import ibis
+
+ # Save original setting
+ original_interactive = ibis.options.interactive
+ ibis.options.interactive = True
+
+ try:
+ # Array scalar like in smoke tests
+ array_scalar = test_table.list.first()
+
+ formatter = get_formatter(array_scalar, include_opinionated=False)
+ assert formatter is not None
+
+ mime, content = formatter(array_scalar)
+ # Complex scalars should use JSON output
+ assert mime == "text/html"
+ assert "<marimo-json-output" in content
+
+ finally:
+ ibis.options.interactive = original_interactive
+
+
+ not HAS_IBIS or not HAS_POLARS, reason="ibis and polars not installed"
+)
+def test_ibis_polars_backend() -> None:
+ """Test ibis with polars backend - SQL tab should show 'Backend doesn't support SQL'."""
+ register_formatters()
+
+ import ibis
+ import polars as pl
+
+ lazy_frame = pl.LazyFrame(
+ {"name": ["Jimmy", "Keith"], "band": ["Led Zeppelin", "Stones"]}
+ )
+ pl_connection = ibis.polars.connect(tables={"band_members": lazy_frame})
+
+ original_interactive = ibis.options.interactive
+ ibis.options.interactive = False
+
+ try:
+ polars_table = pl_connection.table("band_members")
+
+ formatter = get_formatter(polars_table, include_opinionated=False)
+ assert formatter is not None
+
+ mime, content = formatter(polars_table)
+ assert mime == "text/html"
+ assert "<marimo-tabs" in content
+
+ finally:
+ ibis.options.interactive = original_interactive