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: render dataframes in mo.ui.table() by default, add mo.plain (#1697)

Myles Scolnickc6051bef2296
diff --git a/docs/_static/docs-dataframe-output.png b/docs/_static/docs-dataframe-output.png
index b05a2ee98f..bc903c3e12 100644
Binary files a/docs/_static/docs-dataframe-output.png and b/docs/_static/docs-dataframe-output.png differ
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index 245db24dff..65c8192c96 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -11,6 +11,7 @@
justify
lazy
nav_menu
+ plain
routes
sidebar
stacks
@@ -37,6 +38,7 @@ them but just render their children in a certain way.
marimo.lazy
marimo.left
marimo.nav_menu
+ marimo.plain
marimo.right
marimo.routes
marimo.sidebar
diff --git a/docs/api/layouts/plain.md b/docs/api/layouts/plain.md
new file mode 100644
index 0000000000..af8ba18e90
--- /dev/null
+++ b/docs/api/layouts/plain.md
@@ -0,0 +1,5 @@
+# Plain
+
+```{eval-rst}
+.. autofunction:: marimo.plain
+```
diff --git a/docs/guides/dataframes.md b/docs/guides/dataframes.md
index f05ade0211..149c4c00c7 100644
--- a/docs/guides/dataframes.md
+++ b/docs/guides/dataframes.md
@@ -33,6 +33,17 @@ df = pd.read_json(
df
```
+By default the dataframe is displayed using `mo.ui.table`, which provides a
+a rich, interactive table view. You can also use `mo.plain` to revert to the
+to the default HTML representation.
+
+```python
+df = pd.read_json(
+ "https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json"
+)
+mo.plain(df)
+```
+
**Rich displays.**
You can display dataframes in rich tables or charts using the
[`mo.ui.table`](/api/inputs/table/) or [`mo.ui.altair_chart`](/api/plotting/)
diff --git a/marimo/__init__.py b/marimo/__init__.py
index f69e4118b6..e67630ef88 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -41,6 +41,7 @@ __all__ = [
"mpl",
"nav_menu",
"output",
+ "plain",
"plain_text",
"pdf",
"query_params",
@@ -68,7 +69,7 @@ from marimo._ast.app import App
from marimo._ast.cell import Cell
from marimo._islands.island_generator import MarimoIslandGenerator
from marimo._output.doc import doc
-from marimo._output.formatting import as_html
+from marimo._output.formatting import as_html, plain
from marimo._output.hypertext import Html
from marimo._output.justify import center, left, right
from marimo._output.md import md
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
new file mode 100644
index 0000000000..cb109c27f6
--- /dev/null
+++ b/marimo/_output/formatters/df_formatters.py
@@ -0,0 +1,40 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from marimo._messaging.mimetypes import KnownMimeType
+from marimo._output.formatters.formatter_factory import FormatterFactory
+from marimo._plugins.ui._impl.table import table
+
+
+class PolarsFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "polars"
+
+ def register(self) -> None:
+ import polars as pl
+
+ from marimo._output import formatting
+
+ @formatting.opinionated_formatter(pl.DataFrame)
+ def _show_marimo_dataframe(
+ df: pl.DataFrame,
+ ) -> tuple[KnownMimeType, str]:
+ return table(df, selection=None, pagination=True)._mime_()
+
+
+class PyArrowFormatter(FormatterFactory):
+ @staticmethod
+ def package_name() -> str:
+ return "pyarrow"
+
+ def register(self) -> None:
+ import pyarrow as pa
+
+ from marimo._output import formatting
+
+ @formatting.opinionated_formatter(pa.Table)
+ def _show_marimo_dataframe(
+ df: pa.Table,
+ ) -> tuple[KnownMimeType, str]:
+ return table(df, selection=None, pagination=True)._mime_()
diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.py
index 2afe7a2be3..80c82437fd 100644
--- a/marimo/_output/formatters/formatters.py
+++ b/marimo/_output/formatters/formatters.py
@@ -8,6 +8,10 @@ from marimo._output.formatters.altair_formatters import AltairFormatter
from marimo._output.formatters.anywidget_formatters import AnyWidgetFormatter
from marimo._output.formatters.bokeh_formatters import BokehFormatter
from marimo._output.formatters.cell import CellFormatter
+from marimo._output.formatters.df_formatters import (
+ PolarsFormatter,
+ PyArrowFormatter,
+)
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._output.formatters.holoviews_formatters import HoloViewsFormatter
from marimo._output.formatters.ipython_formatters import IPythonFormatter
@@ -25,6 +29,8 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {
AltairFormatter.package_name(): AltairFormatter(),
MatplotlibFormatter.package_name(): MatplotlibFormatter(),
PandasFormatter.package_name(): PandasFormatter(),
+ PolarsFormatter.package_name(): PolarsFormatter(),
+ PyArrowFormatter.package_name(): PyArrowFormatter(),
PlotlyFormatter.package_name(): PlotlyFormatter(),
SeabornFormatter.package_name(): SeabornFormatter(),
LeafmapFormatter.package_name(): LeafmapFormatter(),
diff --git a/marimo/_output/formatters/pandas_formatters.py b/marimo/_output/formatters/pandas_formatters.py
index b1c98699b4..601b7752ce 100644
--- a/marimo/_output/formatters/pandas_formatters.py
+++ b/marimo/_output/formatters/pandas_formatters.py
@@ -6,6 +6,7 @@ from typing import Any
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._output.utils import flatten_string
+from marimo._plugins.ui._impl.table import table
class PandasFormatter(FormatterFactory):
@@ -22,6 +23,12 @@ class PandasFormatter(FormatterFactory):
from marimo._output import formatting
+ @formatting.opinionated_formatter(pd.DataFrame)
+ def _show_marimo_dataframe(
+ df: pd.DataFrame,
+ ) -> tuple[KnownMimeType, str]:
+ return table(df, selection=None, pagination=True)._mime_()
+
@formatting.formatter(pd.DataFrame)
def _show_dataframe(df: pd.DataFrame) -> tuple[KnownMimeType, str]:
max_rows = pd.get_option("display.max_rows")
diff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.py
index 6b3ce69b18..1ffc788206 100644
--- a/marimo/_output/formatting.py
+++ b/marimo/_output/formatting.py
@@ -23,7 +23,7 @@ import traceback
import types
from dataclasses import dataclass
from html import escape
-from typing import Any, Callable, Optional, Tuple, Type, TypeVar
+from typing import Any, Callable, Optional, Tuple, Type, TypeVar, cast
from marimo import _loggers as loggers
from marimo._messaging.mimetypes import KnownMimeType
@@ -38,6 +38,7 @@ T = TypeVar("T")
# we use Tuple instead of the builtin tuple for py3.8 compatibility
Formatter = Callable[[T], Tuple[KnownMimeType, str]]
FORMATTERS: dict[Type[Any], Formatter[Any]] = {}
+OPINIONATED_FORMATTERS: dict[Type[Any], Formatter[Any]] = {}
LOGGER = loggers.marimo_logger()
@@ -63,7 +64,36 @@ def formatter(t: Type[Any]) -> Callable[[Formatter[T]], Formatter[T]]:
return register_format
-def get_formatter(obj: T) -> Optional[Formatter[T]]:
+def opinionated_formatter(
+ t: Type[Any],
+) -> Callable[[Formatter[T]], Formatter[T]]:
+ """Register an opinionated formatter function for a type
+
+ Decorator to register a custom formatter for a given type.
+
+ For example, to register a formatter for a class Foo with a string
+ attribute data:
+
+ ```
+ @opinionated_formatter(Foo)
+ def show_df(foo: Foo) -> tuple[str, str]:
+ return table(foo)._mime_()
+ ```
+ """
+
+ def register_format(f: Formatter[T]) -> Formatter[T]:
+ OPINIONATED_FORMATTERS[t] = f
+ return f
+
+ return register_format
+
+
+def get_formatter(
+ obj: T,
+ # Include opinionated formatters by default
+ # (e.g., for pandas, polars, arrow, etc.)
+ include_opinionated: bool = True,
+) -> Optional[Formatter[T]]:
from marimo._runtime.context import ContextNotInitializedError, get_context
try:
@@ -78,6 +108,20 @@ def get_formatter(obj: T) -> Optional[Formatter[T]]:
# a kernel (eg, in a unit test or when run as a Python script)
register_formatters()
+ if isinstance(obj, Plain):
+ child_formatter = get_formatter(obj.child, include_opinionated=False)
+ if child_formatter:
+
+ def plain_formatter(obj: T) -> tuple[KnownMimeType, str]:
+ assert child_formatter is not None
+ return child_formatter(cast(Plain, obj).child)
+
+ return plain_formatter
+
+ if include_opinionated:
+ if type(obj) in OPINIONATED_FORMATTERS:
+ return OPINIONATED_FORMATTERS[type(obj)]
+
if type(obj) in FORMATTERS:
return FORMATTERS[type(obj)]
elif any(isinstance(obj, t) for t in FORMATTERS.keys()):
@@ -229,3 +273,36 @@ def as_html(value: object) -> Html:
)
else:
raise ValueError(f"Unsupported mimetype {mimetype}")
+
+
+@mddoc
+def plain(value: Any) -> Plain:
+ """
+ Wrap a value to indicate that it should be displayed
+ without any opinionated formatting.
+
+ This is the best way to opt out of marimo's
+ default dataframe rendering.
+
+ **Example.**
+
+ ```python
+ df = data.cars()
+ mo.plain(df)
+ ```
+
+ **Args.**
+
+ - `value`: Any value
+ """
+ return Plain(value)
+
+
+class Plain:
+ """
+ Wrapper around a value to indicate that it should be displayed
+ without any opinionated formatting.
+ """
+
+ def __init__(self, child: Any):
+ self.child = child
diff --git a/marimo/_smoke_tests/bugs/1689.py b/marimo/_smoke_tests/bugs/1689.py
index 0cfedc9636..cd9352cc4e 100644
--- a/marimo/_smoke_tests/bugs/1689.py
+++ b/marimo/_smoke_tests/bugs/1689.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
import marimo
__generated_with = "0.6.23"
diff --git a/marimo/_smoke_tests/plain.py b/marimo/_smoke_tests/plain.py
new file mode 100644
index 0000000000..81d428b5a9
--- /dev/null
+++ b/marimo/_smoke_tests/plain.py
@@ -0,0 +1,48 @@
+# Copyright 2024 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.6.23"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ from vega_datasets import data
+ import polars as pl
+ return data, mo, pl
+
+
+def __(data, pl):
+ df = pl.from_pandas(data.cars())
+ df
+ return df,
+
+
+def __(df, mo):
+ mo.ui.table(df)
+ return
+
+
+def __(df, mo):
+ mo.plain(df)
+ return
+
+
+def __(df, mo):
+ mo.hstack(["hstack", mo.vstack(["vstack", df])])
+ return
+
+
+def __(df, mo):
+ mo.hstack(["hstack", mo.vstack(["vstack", mo.plain(df)])])
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.py
index a68487a2cb..b02af265e6 100644
--- a/tests/_output/formatters/test_formatters.py
+++ b/tests/_output/formatters/test_formatters.py
@@ -3,7 +3,11 @@ from __future__ import annotations
import importlib
import os.path
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
from marimo._output.formatters.formatters import register_formatters
+from marimo._output.formatting import Plain, as_html, get_formatter
def test_path_finder_find_spec() -> None:
@@ -16,3 +20,86 @@ def test_path_finder_find_spec() -> None:
"test_formatters", [os.path.dirname(__file__)]
)
assert spec is not None
+
+
+HAS_DEPS = DependencyManager.has_pandas() and DependencyManager.has_polars()
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_formatters_with_opinionated_formatter() -> None:
+ register_formatters()
+
+ import pandas as pd
+ import polars as pl
+
+ pd_df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
+ pl_df = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
+
+ # Happy path
+ obj = ["test"]
+ formatter = get_formatter(obj)
+ assert formatter
+ assert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')
+
+ # With Plain
+ obj = Plain(["test"])
+ formatter = get_formatter(obj)
+ assert formatter
+ assert formatter(obj) == ("application/json", '["text/plain:\\"test\\""]')
+
+ # With pandas DataFrame
+ formatter = get_formatter(pd_df)
+ assert formatter
+ mime, content = formatter(pd_df)
+ assert mime == "text/html"
+ assert "<marimo-table" in content
+
+ # With plain DataFrame + Plain
+ obj = Plain(pd_df)
+ formatter = get_formatter(obj)
+ assert formatter
+ mime, content = formatter(obj)
+ assert mime == "text/html"
+ assert "<marimo-table" not in content
+
+ # With polars DataFrame
+ formatter = get_formatter(pl_df)
+ assert formatter
+ mime, content = formatter(pl_df)
+ assert mime == "text/html"
+ assert "<marimo-table" in content
+
+ # With plain DataFrame + Plain
+ obj = Plain(pl_df)
+ formatter = get_formatter(obj)
+ assert formatter
+ mime, content = formatter(obj)
+ assert mime == "text/html"
+ assert "<marimo-table" not in content
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_as_html_opinionated_formatter():
+ register_formatters()
+
+ import pandas as pd
+ import polars as pl
+
+ pd_df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
+ pl_df = pl.DataFrame({"A": [1, 2, 3], "B": ["a", "a", "a"]})
+
+ # With pandas DataFrame
+ html = as_html(pd_df)
+ assert "<marimo-table" in html.text
+
+ # With polars DataFrame
+ html = as_html(pl_df)
+ assert "<marimo-table" in html.text
+
+ # With pandas DataFrame + Plain
+ html = as_html(Plain(pd_df))
+ assert "<marimo-table" not in html.text
+
+ # With polars DataFrame + Plain
+ html = as_html(Plain(pl_df))
+ assert "<marimo-table" not in html.text
diff --git a/tests/conftest.py b/tests/conftest.py
index 8e262a5665..9be49f7f34 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -20,12 +20,16 @@ from marimo._messaging.streams import (
ThreadSafeStdout,
ThreadSafeStream,
)
+from marimo._output.formatters.formatters import register_formatters
from marimo._runtime.context import teardown_context
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.marimo_pdb import MarimoPdb
from marimo._runtime.requests import AppMetadata, ExecutionRequest
from marimo._runtime.runtime import Kernel
+# register import hooks for third-party module formatters
+register_formatters()
+
@dataclasses.dataclass
class _MockStream(ThreadSafeStream):