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: use mo.inspect in formatters for some basic types (#6541)

Myles Scolnickc9836a26c80d
diff --git a/marimo/_output/formatters/structures.py b/marimo/_output/formatters/structures.py
index 085f374232..cea108ee4f 100644
--- a/marimo/_output/formatters/structures.py
+++ b/marimo/_output/formatters/structures.py
@@ -10,7 +10,8 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output import formatting
from marimo._output.formatters.formatter_factory import FormatterFactory
from marimo._output.formatters.repr_formatters import maybe_get_repr_formatter
-from marimo._plugins.stateless import plain_text
+from marimo._plugins.stateless.inspect import inspect
+from marimo._plugins.stateless.plain_text import plain_text
from marimo._utils.flatten import CyclicStructureError, flatten
@@ -84,20 +85,20 @@ class StructuresFormatter(FormatterFactory):
# e.g. sys.version_info
if isinstance(t, tuple) and type(t) is not tuple:
if str(t) != str(tuple(t)):
- return plain_text.plain_text(str(t))._mime_()
+ return plain_text(str(t))._mime_()
elif isinstance(t, list) and type(t) is not list:
if str(t) != str(list(t)):
- return plain_text.plain_text(str(t))._mime_()
+ return plain_text(str(t))._mime_()
elif (
isinstance(t, dict)
and type(t) is not dict
and type(t) is not defaultdict
):
if str(t) != str(dict(t)):
- return plain_text.plain_text(str(t))._mime_()
+ return plain_text(str(t))._mime_()
elif isinstance(t, defaultdict) and type(t) is not defaultdict:
if str(t) != str(defaultdict(t.default_factory, t)):
- return plain_text.plain_text(str(t))._mime_()
+ return plain_text(str(t))._mime_()
if t and "matplotlib" in sys.modules:
# Special case for matplotlib:
@@ -122,3 +123,22 @@ class StructuresFormatter(FormatterFactory):
return ("text/plain", str(t))
return ("application/json", json.dumps(formatted_structure))
+
+ import types
+
+ @formatting.formatter(types.BuiltinFunctionType)
+ @formatting.formatter(types.BuiltinMethodType)
+ @formatting.formatter(types.FunctionType)
+ @formatting.formatter(types.LambdaType)
+ @formatting.formatter(types.MethodType)
+ def _format_function(obj: Any) -> tuple[KnownMimeType, str]:
+ try:
+ # If the function has a repr_formatter, use it
+ repr_formatter = maybe_get_repr_formatter(obj)
+ if repr_formatter is not None:
+ return repr_formatter(obj)
+ # Otherwise, use the pretty inspect
+ return inspect(obj, value=False)._mime_()
+ except Exception:
+ # If it fails, fallback to just 'repr'
+ return plain_text(repr(obj))._mime_()
diff --git a/marimo/_plugins/stateless/inspect.py b/marimo/_plugins/stateless/inspect.py
index 3912be14aa..51219f5748 100644
--- a/marimo/_plugins/stateless/inspect.py
+++ b/marimo/_plugins/stateless/inspect.py
@@ -9,18 +9,7 @@ from marimo._output.formatting import as_html
from marimo._output.hypertext import Html
-def inspect(
- obj: object,
- *,
- help: bool = False, # noqa: A002
- methods: bool = False,
- docs: bool = True,
- private: bool = False,
- dunder: bool = False,
- sort: bool = True,
- all: bool = False, # noqa: A002
- value: bool = True,
-) -> Html:
+class inspect(Html):
"""Inspect a Python object.
Displays objects with their attributes, methods, and documentation
@@ -45,169 +34,196 @@ def inspect(
mo.inspect(obj, methods=True)
```
"""
- if all:
- methods = True
- private = True
- dunder = True
- type_label, name = _get_object_title(obj)
-
- type_colors = {
- "class": ("background-color: var(--blue-3); color: var(--blue-11);"),
- "function": (
- "background-color: var(--green-3); color: var(--green-11);"
- ),
- "method": (
- "background-color: var(--purple-3); color: var(--purple-11);"
- ),
- "module": (
- "background-color: var(--orange-3); color: var(--orange-11);"
- ),
- "instance": (
- "background-color: var(--crimson-3); color: var(--crimson-11);"
- ),
- "object": (
- "background-color: var(--slate-3); color: var(--slate-11);"
- ),
- }
+ def __init__(
+ self,
+ obj: object,
+ *,
+ help: bool = False, # noqa: A002
+ methods: bool = False,
+ docs: bool = True,
+ private: bool = False,
+ dunder: bool = False,
+ sort: bool = True,
+ all: bool = False, # noqa: A002
+ value: bool = True,
+ ) -> None:
+ self._obj = obj
+ if all:
+ methods = True
+ private = True
+ dunder = True
+
+ type_label, name = _get_object_title(obj)
+
+ type_colors = {
+ "class": (
+ "background-color: var(--blue-3); color: var(--blue-11);"
+ ),
+ "function": (
+ "background-color: var(--green-3); color: var(--green-11);"
+ ),
+ "method": (
+ "background-color: var(--purple-3); color: var(--purple-11);"
+ ),
+ "module": (
+ "background-color: var(--orange-3); color: var(--orange-11);"
+ ),
+ "instance": (
+ "background-color: var(--crimson-3); color: var(--crimson-11);"
+ ),
+ "object": (
+ "background-color: var(--slate-3); color: var(--slate-11);"
+ ),
+ }
- pill_style = type_colors.get(type_label, type_colors["object"])
+ pill_style = type_colors.get(type_label, type_colors["object"])
- docstring = inspect_.getdoc(obj) if docs else None
- if docstring and not help:
- docstring = docstring.split("\n\n")[0]
+ docstring = inspect_.getdoc(obj) if docs else None
+ if docstring and not help:
+ docstring = docstring.split("\n\n")[0]
- attributes = _get_filtered_attributes(obj, methods, private, dunder)
- if sort:
- attributes.sort(key=lambda x: x[0])
+ attributes = _get_filtered_attributes(obj, methods, private, dunder)
+ if sort:
+ attributes.sort(key=lambda x: x[0])
- header = h.div(
- [
- h.span(
- html.escape(type_label),
- style=(
- pill_style + "padding: 2px 8px; "
- "border-radius: 4px; "
- "font-family: monospace; "
- "font-size: 0.75rem; "
- "font-weight: 600; "
- "margin-right: 8px; "
- "display: inline-block;"
+ header = h.div(
+ [
+ h.span(
+ html.escape(type_label),
+ style=(
+ pill_style + "padding: 2px 8px; "
+ "border-radius: 4px; "
+ "font-family: monospace; "
+ "font-size: 0.75rem; "
+ "font-weight: 600; "
+ "margin-right: 8px; "
+ "display: inline-block;"
+ ),
),
- ),
- h.span(
- html.escape(name),
- style=(
- "font-family: monospace; "
- "font-size: 0.875rem; "
- "color: var(--slate-12);"
+ h.span(
+ html.escape(name),
+ style=(
+ "font-family: monospace; "
+ "font-size: 0.875rem; "
+ "color: var(--slate-12);"
+ ),
),
- ),
- ],
- style=(
- "padding: 10px 12px 8px 12px; display: flex; align-items: center;"
- ),
- )
-
- main_content = []
-
- # Add divider after header
- main_content.append(
- h.div(
- "", # Empty string for divider line
+ ],
style=(
- "height: 1px; "
- "background-color: var(--slate-3); "
- "margin: 0 12px 8px 12px;"
+ "padding: 10px 12px 8px 12px; display: flex; align-items: center;"
),
)
- )
- if docstring:
- doc_style = (
- "color: var(--slate-11); "
- "margin: 0 12px 8px 12px; "
- "font-size: 0.75rem; "
- "font-family: monospace; "
- "padding: 0; "
- "white-space: pre-wrap;"
+ main_content: list[str] = []
+
+ # Add divider after header
+ main_content.append(
+ h.div(
+ "", # Empty string for divider line
+ style=(
+ "height: 1px; "
+ "background-color: var(--slate-3); "
+ "margin: 0 12px 8px 12px;"
+ ),
+ )
)
- main_content.append(h.div(html.escape(docstring), style=doc_style))
-
- if value and not inspect_.isclass(obj) and not callable(obj):
- main_content.append(_render_value(obj))
-
- if callable(obj):
- sig = _get_signature(obj)
- if sig:
- if inspect_.isfunction(obj) or inspect_.ismethod(obj):
- # For functions/methods, show the full definition
- func_name = obj.__name__ if hasattr(obj, "__name__") else ""
- prefix = (
- "async def" if inspect_.iscoroutinefunction(obj) else "def"
- )
- main_content.append(
- h.div(
- h.span(
- f"{prefix} {html.escape(func_name)}{html.escape(sig)}:"
- ),
- style=(
- "font-family: monospace; "
- "font-size: 0.875rem; "
- "color: var(--slate-12); "
- "margin: 0 12px 8px 12px;"
- ),
+
+ if docstring:
+ doc_style = (
+ "color: var(--slate-11); "
+ "margin: 0 12px 8px 12px; "
+ "font-size: 0.75rem; "
+ "font-family: monospace; "
+ "padding: 0; "
+ "white-space: pre-wrap;"
+ )
+ main_content.append(h.div(html.escape(docstring), style=doc_style))
+
+ if value and not inspect_.isclass(obj) and not callable(obj):
+ main_content.append(_render_value(obj))
+
+ if callable(obj):
+ sig = _get_signature(obj)
+ if sig:
+ if inspect_.isfunction(obj) or inspect_.ismethod(obj):
+ # For functions/methods, show the full definition
+ func_name = (
+ obj.__name__ if hasattr(obj, "__name__") else ""
)
- )
- else:
- # For other callables (classes, etc), just show the signature
- main_content.append(
- h.div(
- h.pre(
- html.escape(sig),
- style="color: var(--slate-12); overflow-x: auto; margin: 0;",
- ),
- style=(
- "background-color: var(--background); "
- "border: 1px solid var(--slate-3); "
- "border-radius: 4px; "
- "padding: 8px 10px; "
- "margin: 0 12px 8px 12px; "
- "font-family: monospace; "
- "font-size: 0.875rem;"
- ),
+ prefix = (
+ "async def"
+ if inspect_.iscoroutinefunction(obj)
+ else "def"
)
+ main_content.append(
+ h.div(
+ h.span(
+ f"{prefix} {html.escape(func_name)}{html.escape(sig)}:"
+ ),
+ style=(
+ "font-family: monospace; "
+ "font-size: 0.875rem; "
+ "color: var(--slate-12); "
+ "margin: 0 12px 8px 12px;"
+ ),
+ )
+ )
+ else:
+ # For other callables (classes, etc), just show the signature
+ main_content.append(
+ h.div(
+ h.pre(
+ html.escape(sig),
+ style="color: var(--slate-12); overflow-x: auto; margin: 0;",
+ ),
+ style=(
+ "background-color: var(--background); "
+ "border: 1px solid var(--slate-3); "
+ "border-radius: 4px; "
+ "padding: 8px 10px; "
+ "margin: 0 12px 8px 12px; "
+ "font-family: monospace; "
+ "font-size: 0.875rem;"
+ ),
+ )
+ )
+
+ if attributes:
+ table_rows = []
+ for name, value, attr_type, error in attributes:
+ table_rows.append(
+ _render_attribute_row(name, value, attr_type, error, docs)
)
- if attributes:
- table_rows = []
- for name, value, attr_type, error in attributes:
- table_rows.append(
- _render_attribute_row(name, value, attr_type, error, docs)
+ main_content.append(
+ h.div(
+ h.table(h.tbody(table_rows)),
+ style=(
+ "overflow-x: auto; font-size: 0.875rem; padding: 0 0 8px 0;"
+ ),
+ )
)
- main_content.append(
+ super().__init__(
h.div(
- h.table(h.tbody(table_rows)),
+ [header] + main_content if main_content else [header],
style=(
- "overflow-x: auto; font-size: 0.875rem; padding: 0 0 8px 0;"
+ "border-radius: 6px; "
+ "overflow: hidden; "
+ "background-color: var(--slate-1); "
+ "display: inline-block; "
+ "min-width: 0; "
+ "max-width: 100%;"
),
)
)
- return Html(
- h.div(
- [header] + main_content if main_content else [header],
- style=(
- "border-radius: 6px; "
- "overflow: hidden; "
- "background-color: var(--slate-1); "
- "display: inline-block; "
- "min-width: 0; "
- "max-width: 100%;"
- ),
- )
- )
+ def _repr_md_(self) -> str:
+ try:
+ return repr(self._obj)
+ except Exception:
+ return self.text
def _get_object_title(obj: object) -> tuple[str, str]:
diff --git a/marimo/_smoke_tests/formatters/inspect_things.py b/marimo/_smoke_tests/formatters/inspect_things.py
new file mode 100644
index 0000000000..b1389c66fb
--- /dev/null
+++ b/marimo/_smoke_tests/formatters/inspect_things.py
@@ -0,0 +1,121 @@
+import marimo
+
+__generated_with = "0.16.2"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import numpy as np
+ import functools
+ return functools, mo, np
+
+
+def _(mo):
+ mo.inspect(mo, value=False)
+ return
+
+
+def _(mo, np):
+ mo.inspect(np)
+ return
+
+
+def _():
+ def fib(n):
+ """Return the nth Fibonacci number"""
+ if n <= 1:
+ return n
+ else:
+ a, b = 0, 1
+ for _ in range(n - 1):
+ a, b = b, a + b
+ return b
+
+
+ fib
+ return
+
+
+class Foo:
+ def __init__(self):
+ pass
+
+ def __str__():
+ pass
+
+ def bar():
+ pass
+
+ def _baz():
+ pass
+
+
+def _():
+ Foo
+ return
+
+
+def _():
+ Foo.__init__
+ return
+
+
+def _():
+ Foo.__str__
+ return
+
+
+def _():
+ Foo.bar
+ return
+
+
+def _():
+ Foo().bar
+ return
+
+
+def _():
+ Foo._baz
+ return
+
+
+def _(functools):
+ @functools.cache
+ def square(x):
+ return x * x
+
+
+ square
+ return
+
+
+def _():
+ lambda_func = lambda x: x * 2
+ lambda_func
+ return
+
+
+def _():
+ # built in
+ len
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_output/formatters/test_structures.py b/tests/_output/formatters/test_structures.py
index 6c11504ebb..22280674ad 100644
--- a/tests/_output/formatters/test_structures.py
+++ b/tests/_output/formatters/test_structures.py
@@ -257,3 +257,90 @@ def test_format_structure_defaultdict() -> None:
"application/json",
'{"a": [1], "b": [2], "c": []}',
)
+
+
+def test_function_like_objects_are_pretty_inspected() -> None:
+ from marimo._output.formatters.structures import StructuresFormatter
+
+ StructuresFormatter().register()
+
+ # Regular function
+ def foo(x: int, y: str = "a") -> str: # noqa: ARG001
+ return "ok"
+
+ fmt = get_formatter(foo)
+ assert fmt is not None
+ mime, data = fmt(foo)
+ assert mime == "text/html"
+ assert "function" in data or "def foo(" in data
+
+ # Lambda
+ lam = lambda z: z # noqa: E731
+ fmt = get_formatter(lam)
+ assert fmt is not None
+ mime, data = fmt(lam)
+ assert mime == "text/html"
+ assert "function" in data or "lambda" in data or "def" in data
+
+ # Builtin function
+ fmt = get_formatter(len)
+ assert fmt is not None
+ mime, data = fmt(len)
+ assert mime == "text/html"
+ # Builtins are labeled as instances of builtin_function_or_method
+ assert "builtin_function_or_method" in data or "instance" in data
+
+ # Method
+ class C:
+ def m(self, a: int) -> int: # noqa: D401, ARG002
+ return a
+
+ fmt = get_formatter(C.m)
+ assert fmt is not None
+ mime, data = fmt(C.m)
+ assert mime == "text/html"
+ assert "def m(" in data or "method" in data
+
+
+def test_function_like_objects_use_repr_formatter_if_present() -> None:
+ # Register a temporary repr formatter on a simple callable class
+ class D:
+ def __call__(self) -> None: # pragma: no cover - just shape
+ return None
+
+ def _repr_html_(self) -> str:
+ return "<b>HELLO</b>"
+
+ # Ensure base structure formatter is registered
+ from marimo._output.formatters.structures import StructuresFormatter
+
+ StructuresFormatter().register()
+
+ # The repr formatter should be honored and returned directly
+ obj = D()
+ fmt = get_formatter(obj)
+ assert fmt is not None
+ mime, data = fmt(obj)
+ assert mime == "text/html"
+ assert data == "<b>HELLO</b>"
+
+
+def test_function_like_objects_fallback_on_exception() -> None:
+ # Build a callable that raises when inspected/signatured to force fallback
+ class Boom:
+ def __call__(self, *args: object, **kwargs: object) -> None: # noqa: ARG002
+ return None
+
+ b = Boom().__call__
+
+ from marimo._output.formatters.structures import StructuresFormatter
+
+ StructuresFormatter().register()
+ fmt = get_formatter(b)
+ assert fmt is not None
+ mime, data = fmt(b)
+ assert mime == "text/html" or mime == "text/plain"
+ # Fallback path returns plain text repr wrapped via plain_text
+ # which ultimately produces HTML; accept either to be robust.
+ assert isinstance(data, str)
+ assert len(data) > 0
diff --git a/tests/_plugins/stateless/test_inspect.py b/tests/_plugins/stateless/test_inspect.py
index e55978a2af..4e0bd30679 100644
--- a/tests/_plugins/stateless/test_inspect.py
+++ b/tests/_plugins/stateless/test_inspect.py
@@ -1,6 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import dataclass
+
from marimo._plugins.stateless.inspect import inspect
@@ -206,3 +208,23 @@ def test_inspect_sort_attributes() -> None:
assert "<table" in sorted_html
assert "<table" in unsorted_html
+
+
+def test_inspect_repr_md() -> None:
+ @dataclass
+ class Value:
+ value: str
+
+ result = inspect(Value(value="one"))
+ md = result._repr_md_()
+ assert md == repr(Value(value="one"))
+
+
+def test_inspect_repr_md_error() -> None:
+ class ReprError:
+ def __repr__(self):
+ raise Exception("repr error") # noqa: TRY002
+
+ result = inspect(ReprError())
+ md = result._repr_md_()
+ assert "<div" in md