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
Add `mo.inspect` for rich object introspection (#5936)
Trevor Manz176314146160
diff --git a/docs/api/inspect.md b/docs/api/inspect.mdnew file mode 100644index 0000000000..7018401aaf--- /dev/null+++ b/docs/api/inspect.md@@ -0,0 +1,21 @@+# Inspect++Use `mo.inspect()` to explore Python objects with a rich, interactive display of their attributes, methods, and documentation.++## Example++```python+import marimo as mo++# Inspect a class+mo.inspect(list, methods=True)++# Inspect an instance+my_dict = {"key": "value"}+mo.inspect(my_dict)++# Show all attributes including private and dunder+mo.inspect(my_dict, all=True)+```++::: marimo.inspect\ No newline at end of filediff --git a/docs/api/outputs.md b/docs/api/outputs.mdindex 2fae22d5a1..ee442edffc 100644--- a/docs/api/outputs.md+++ b/docs/api/outputs.md@@ -52,3 +52,8 @@ functions for capturing console outputs and redirecting them to cell outputs.::: marimo.capture_stdout::: marimo.capture_stderr++## Object inspection++Use [`mo.inspect`][marimo.inspect] to create a rich display of Python objects+for exploring their attributes, methods, and documentation.diff --git a/docs/guides/outputs.md b/docs/guides/outputs.mdindex eefa8bc6a1..b55d7aa43a 100644--- a/docs/guides/outputs.md+++ b/docs/guides/outputs.md@@ -170,6 +170,14 @@ for i in mo.status.progress_bar(range(10)):marimo comes with functions to display media, including images, audio,video, pdfs, and more. See the [API docs](../api/media/index.md) for more info.+## Inspecting objects++marimo has built-in formatters for many objects, but sometimes the default+representation isn't useful (e.g., `<MyClass at 0x...>`). In these cases, use+[`mo.inspect()`][marimo.inspect] to explore an object's attributes, methods,+and documentation as an output. See the [API+docs](../api/outputs.md#object-inspection) for more details.+## Imperatively adding outputsWhile a cell's output is its last expression, it can at times be helpfuldiff --git a/marimo/__init__.py b/marimo/__init__.pyindex c5e610a443..22d097e8dd 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -48,6 +48,7 @@ __all__ = ["iframe","image","image_compare",+ "inspect","json","latex","lazy",@@ -109,6 +110,7 @@ from marimo._plugins.stateless.flex import hstack, vstackfrom marimo._plugins.stateless.icon import iconfrom marimo._plugins.stateless.image import imagefrom marimo._plugins.stateless.image_compare import image_compare+from marimo._plugins.stateless.inspect import inspectfrom marimo._plugins.stateless.json_component import jsonfrom marimo._plugins.stateless.lazy import lazyfrom marimo._plugins.stateless.mermaid import mermaiddiff --git a/marimo/_output/builder.py b/marimo/_output/builder.pyindex 4c40d42503..ce338ec239 100644--- a/marimo/_output/builder.py+++ b/marimo/_output/builder.py@@ -187,6 +187,120 @@ class _HTMLBuilder:else:return f"<figcaption {_join_params(params)}>{children_html}</figcaption>"+ @staticmethod+ def h3(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<h3>{children_html}</h3>"+ else:+ return f"<h3 {_join_params(params)}>{children_html}</h3>"++ @staticmethod+ def span(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<span>{children_html}</span>"+ else:+ return f"<span {_join_params(params)}>{children_html}</span>"++ @staticmethod+ def table(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<table>{children_html}</table>"+ else:+ return f"<table {_join_params(params)}>{children_html}</table>"++ @staticmethod+ def tbody(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<tbody>{children_html}</tbody>"+ else:+ return f"<tbody {_join_params(params)}>{children_html}</tbody>"++ @staticmethod+ def tr(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<tr>{children_html}</tr>"+ else:+ return f"<tr {_join_params(params)}>{children_html}</tr>"++ @staticmethod+ def td(+ children: Union[str, list[str]], *, style: Optional[str] = None+ ) -> str:+ resolved_children = (+ [children] if isinstance(children, str) else children+ )++ params: list[tuple[str, Union[str, None]]] = []+ if style:+ params.append(("style", style))++ children_html = "".join(resolved_children)++ if len(params) == 0:+ return f"<td>{children_html}</td>"+ else:+ return f"<td {_join_params(params)}>{children_html}</td>"+def _join_params(params: list[tuple[str, Union[str, None]]]) -> str:# Filter Nonediff --git a/marimo/_plugins/stateless/inspect.py b/marimo/_plugins/stateless/inspect.pynew file mode 100644index 0000000000..3912be14aa--- /dev/null+++ b/marimo/_plugins/stateless/inspect.py@@ -0,0 +1,467 @@+# Copyright 2025 Marimo. All rights reserved.+from __future__ import annotations++import html+import inspect as inspect_++from marimo._output.builder import h+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:+ """Inspect a Python object.++ Displays objects with their attributes, methods, and documentation+ in a rich HTML format. Useful for exploring objects that lack a rich repr.++ Args:+ obj: The object to inspect.+ help: Show full help text (otherwise just first paragraph).+ methods: Show methods.+ docs: Show documentation for attributes/methods.+ private: Show private attributes (starting with '_').+ dunder: Show dunder attributes (starting with '__').+ sort: Sort attributes alphabetically.+ all: Show all attributes (methods, private, and dunder).+ value: Show the object's value/repr.++ Returns:+ An `Html` object.++ Example:+ ```python+ 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);"+ ),+ }++ 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]++ 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;"+ ),+ ),+ 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;"+ ),+ )+ )++ 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 ""+ 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)+ )++ main_content.append(+ h.div(+ h.table(h.tbody(table_rows)),+ style=(+ "overflow-x: auto; font-size: 0.875rem; padding: 0 0 8px 0;"+ ),+ )+ )++ 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 _get_object_title(obj: object) -> tuple[str, str]:+ """Returns (type_label, name) for the object."""+ if inspect_.isclass(obj):+ module = obj.__module__+ if module and module != "__builtin__":+ return ("class", f"{module}.{obj.__name__}")+ return ("class", obj.__name__)+ elif inspect_.isfunction(obj):+ name = obj.__name__ if hasattr(obj, "__name__") else "function"+ return ("function", name)+ elif inspect_.ismethod(obj):+ name = obj.__name__ if hasattr(obj, "__name__") else "method"+ return ("method", name)+ elif inspect_.ismodule(obj):+ return (+ "module",+ obj.__name__ if hasattr(obj, "__name__") else "module",+ )+ elif hasattr(obj, "__class__"):+ cls = obj.__class__+ module = cls.__module__+ if module and module != "__builtin__":+ return ("instance", f"{module}.{cls.__name__}")+ return ("instance", cls.__name__)+ else:+ return ("object", type(obj).__name__)+++def _get_signature(obj: object) -> str | None:+ try:+ sig = inspect_.signature(obj) # type: ignore+ prefix = "async " if inspect_.iscoroutinefunction(obj) else ""+ return f"{prefix}{sig}"+ except (ValueError, TypeError):+ return None+++def _get_filtered_attributes(+ obj: object, methods: bool, private: bool, dunder: bool+) -> list[tuple[str, bool, str, Exception | None]]:+ attributes: list[tuple[str, bool, str, Exception | None]] = []++ try:+ all_attrs = dir(obj)+ except Exception:+ return attributes++ for name in all_attrs:+ if name.startswith("__") and not dunder:+ continue+ if name.startswith("_") and not name.startswith("__") and not private:+ continue++ try:+ value = getattr(obj, name)+ error = None+ except Exception as e:+ value = None+ error = e++ if error is not None:+ attr_type = "error"+ elif _is_property(obj, name):+ attr_type = "property"+ elif callable(value):+ if not methods:+ continue+ attr_type = "method"+ else:+ attr_type = "attribute"++ attributes.append((name, value, attr_type, error))++ return attributes+++def _is_property(obj: object, name: str) -> bool:+ for cls in inspect_.getmro(type(obj)):+ if name in cls.__dict__ and isinstance(cls.__dict__[name], property):+ return True+ return False+++def _render_value(obj: object) -> str:+ container_style = (+ "background-color: var(--background); "+ "border: 1px solid var(--slate-3); "+ "border-radius: 4px; "+ "padding: 8px 10px; "+ "margin: 0 12px 8px 12px; "+ "overflow-x: auto; "+ "overflow-y: hidden;"+ )++ # Try to get HTML representation+ try:+ html_obj = as_html(obj)+ _, data = html_obj._mime_()+ return h.div(data, style=container_style)+ except Exception:+ # Fall back to repr+ pass++ try:+ value_repr = html.escape(repr(obj))+ except Exception as e:+ value_repr = f"<repr-error {html.escape(str(e))}>"++ return h.div(+ h.pre(+ value_repr,+ style="color: var(--slate-12); white-space: pre; margin: 0; font-family: monospace; font-size: 0.875rem;",+ ),+ style=container_style,+ )+++def _render_attribute_row(+ name: str,+ value: object,+ attr_type: str,+ error: Exception | None,+ docs: bool,+) -> str:+ name_style_base = (+ "padding: 2px 8px 2px 12px; "+ "vertical-align: top; "+ "text-align: right; "+ "font-family: monospace; "+ "font-size: 0.75rem; "+ "white-space: nowrap; "+ "line-height: 1.5; "+ "color: var(--slate-10);"+ )++ equals_style = (+ "padding: 2px 4px; "+ "color: var(--slate-9); "+ "vertical-align: top; "+ "font-family: monospace; "+ "font-size: 0.75rem; "+ "line-height: 1.5;"+ )++ if error is not None:+ name_style = name_style_base + " color: var(--red-11);"+ error_repr = f'<span style="color: var(--red-11); font-family: monospace; font-size: 0.75rem;"><{type(error).__name__}: {html.escape(str(error))}></span>'+ return h.tr(+ [+ h.td(html.escape(name), style=name_style),+ h.td("=", style=equals_style),+ h.td(+ error_repr,+ style="color: var(--red-11); vertical-align: top; line-height: 1.5; padding: 2px 12px 2px 4px;",+ ),+ ]+ )+ elif attr_type == "method":+ name_style = name_style_base+ display = _format_method(name, value, docs)+ return h.tr(+ [+ h.td(html.escape(name), style=name_style),+ h.td("=", style=equals_style),+ h.td(+ h.span(html.escape(display), style="white-space: pre;"),+ style=(+ "color: var(--slate-11); "+ "font-family: monospace; "+ "font-size: 0.75rem; "+ "vertical-align: top; "+ "line-height: 1.5; "+ "padding: 2px 12px 2px 4px;"+ ),+ ),+ ]+ )+ else:+ name_style = name_style_base+ if attr_type == "property":+ name_style += " font-style: italic;"+ value_html = _render_value_inline(value)+ return h.tr(+ [+ h.td(html.escape(name), style=name_style),+ h.td("=", style=equals_style),+ h.td(+ value_html,+ style="color: var(--foreground); vertical-align: top; line-height: 1.5; padding: 2px 12px 2px 4px;",+ ),+ ]+ )+++def _format_method(name: str, method: object, docs: bool) -> str:+ try:+ sig = inspect_.signature(method) # type: ignore+ if inspect_.iscoroutinefunction(method):+ display = f"async def {name}{sig}"+ else:+ display = f"def {name}{sig}"+ except Exception:+ display = f"def {name}(...)"++ if docs:+ doc = inspect_.getdoc(method)+ if doc:+ first_line = doc.split("\n")[0]+ if len(first_line) > 80:+ first_line = first_line[:77] + "..."+ display += f": {first_line}"++ return display+++def _render_value_inline(value: object) -> str:+ if isinstance(value, str):+ # Colors from @textea/json-viewer string rendering+ # Light mode: #cb4b16, Dark mode: #dc9656+ return h.span(+ f'"{html.escape(value)}"',+ style="color: light-dark(#cb4b16, #dc9656); font-family: monospace; font-size: 0.75rem;",+ )++ if isinstance(value, (int, float, bool, type(None))):+ return h.span(+ html.escape(str(value)),+ style="font-family: monospace; font-size: 0.75rem;",+ )++ # Try to get HTML representation+ try:+ html_obj = as_html(value)+ _, data = html_obj._mime_()+ if isinstance(value, (dict, list, tuple)):+ return h.div(+ data, style="font-size: 0.75rem; display: inline-block;"+ )+ return h.span(data, style="display: inline-block;")+ except Exception:+ # Fall back to repr+ pass++ try:+ value_str = repr(value)+ except Exception as e:+ value_str = f"<repr-error {str(e)}>"++ if len(value_str) > 200:+ value_str = value_str[:197] + "..."++ return h.span(+ html.escape(value_str),+ style="font-family: monospace; font-size: 0.75rem;",+ )diff --git a/tests/_plugins/stateless/test_inspect.py b/tests/_plugins/stateless/test_inspect.pynew file mode 100644index 0000000000..e55978a2af--- /dev/null+++ b/tests/_plugins/stateless/test_inspect.py@@ -0,0 +1,208 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._plugins.stateless.inspect import inspect+++class SimpleClass:+ """A simple test class."""++ def __init__(self):+ self.value = 42+ self._private = "hidden"+ self.__dunder = "very hidden"++ def method(self):+ """A public method."""+ pass++ def _private_method(self):+ """A private method."""+ pass+++def simple_function(x: int, y: str = "default") -> str:+ """A simple test function."""+ return f"{x} - {y}"+++def test_inspect_basic_object() -> None:+ obj = SimpleClass()+ result = inspect(obj)+ html = result.text++ assert "instance" in html+ assert "SimpleClass" in html+ assert "42" in html+ assert "<div" in html+ assert "style=" in html+++def test_inspect_with_docstring() -> None:+ result = inspect(SimpleClass)+ html = result.text+ assert "A simple test class" in html+++def test_inspect_function() -> None:+ result = inspect(simple_function)+ html = result.text++ assert "function" in html+ assert "simple_function" in html+ # The signature may have HTML-escaped quotes or formatted differently+ assert "x:" in html+ assert "int" in html+ assert "y:" in html+ assert "str" in html+++def test_inspect_with_methods() -> None:+ obj = SimpleClass()+ result = inspect(obj, methods=True)+ html = result.text+ assert "method" in html+++def test_inspect_with_private() -> None:+ obj = SimpleClass()+ result = inspect(obj, private=True)+ html = result.text+ assert "_private" in html+++def test_inspect_with_dunder() -> None:+ obj = SimpleClass()+ result = inspect(obj, dunder=True)+ html_str = result.text+ assert "_SimpleClass__dunder" in html_str or "__" in html_str++ result_with_all = inspect(obj, all=True)+ html_with_all = result_with_all.text+ assert "_SimpleClass__dunder" in html_with_all or "__" in html_with_all+++def test_inspect_string_value() -> None:+ # When inspecting a string directly, it shows as an instance of str+ result = inspect("test string", value=True)+ html = result.text+ assert "test string" in html+ assert "instance" in html+ assert "str" in html++ # String coloring is used when strings appear in attributes+ class WithString:+ def __init__(self):+ self.text = "colored string"++ result2 = inspect(WithString())+ html2 = result2.text+ assert "light-dark(#cb4b16, #dc9656)" in html2+++def test_inspect_dict() -> None:+ test_dict = {"key": "value", "number": 42}+ result = inspect(test_dict)+ html = result.text+ assert "dict" in html.lower() or "instance" in html+++def test_inspect_list() -> None:+ test_list = [1, 2, 3, "test"]+ result = inspect(test_list)+ html = result.text+ assert "list" in html.lower() or "instance" in html+++def test_inspect_module() -> None:+ import os++ result = inspect(os, methods=False)+ html = result.text+ assert "module" in html+ assert "os" in html+++def test_inspect_html_escaping() -> None:+ class HTMLTest:+ def __init__(self):+ self.value = "<script>alert('xss')</script>"++ obj = HTMLTest()+ result = inspect(obj)+ html = result.text++ assert "<script>" in html or "<" in html+ assert "<script>alert" not in html+++def test_inspect_no_value() -> None:+ obj = SimpleClass()+ result = inspect(obj, value=False)+ html = result.text+ assert "<div" in html+++def test_inspect_css_variables() -> None:+ result = inspect(SimpleClass())+ html = result.text++ assert "var(--" in html+ assert any(+ var in html+ for var in [+ "var(--slate-",+ "var(--background)",+ "var(--foreground)",+ "var(--blue-",+ "var(--green-",+ "var(--purple-",+ ]+ )+++def test_inspect_type_pills() -> None:+ class_result = inspect(SimpleClass)+ assert "var(--blue-" in class_result.text++ func_result = inspect(simple_function)+ assert "var(--green-" in func_result.text++ instance_result = inspect(SimpleClass())+ assert "var(--crimson-" in instance_result.text++ import os++ module_result = inspect(os)+ assert "var(--orange-" in module_result.text+++def test_inspect_divider() -> None:+ result = inspect(SimpleClass(), value=True)+ html = result.text+ # Check for the divider (could be single or double quotes)+ assert "height: 1px;" in html+ assert "var(--slate-3)" in html+++def test_inspect_sort_attributes() -> None:+ class UnsortedClass:+ def __init__(self):+ self.zebra = 1+ self.apple = 2+ self.middle = 3++ obj = UnsortedClass()++ sorted_result = inspect(obj, sort=True)+ sorted_html = sorted_result.text++ unsorted_result = inspect(obj, sort=False)+ unsorted_html = unsorted_result.text++ for attr in ["zebra", "apple", "middle"]:+ assert attr in sorted_html+ assert attr in unsorted_html++ assert "<table" in sorted_html+ assert "<table" in unsorted_htmldiff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txtindex 430cf0f4e0..629ebce650 100644--- a/tests/snapshots/api.txt+++ b/tests/snapshots/api.txt@@ -35,6 +35,7 @@ iconiframeimageimage_compare+inspectislandsMarimoIslandGeneratorMarimoIslandStub