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.

fix: handle objects with `__getattr__` returning non-callable values in serialization (#8109)

Myles Scolnick43f35eb772ea
diff --git a/marimo/_messaging/msgspec_encoder.py b/marimo/_messaging/msgspec_encoder.py
index fea3ca5719..026bd55ba0 100644
--- a/marimo/_messaging/msgspec_encoder.py
+++ b/marimo/_messaging/msgspec_encoder.py
@@ -18,6 +18,7 @@ import msgspec.json
from marimo import _loggers
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.core.media import io_to_data_url
+from marimo._utils.methods import getcallable
LOGGER = _loggers.marimo_logger()
@@ -25,11 +26,11 @@ LOGGER = _loggers.marimo_logger()
def enc_hook(obj: Any) -> Any:
"""Custom encoding hook for marimo types."""
- if hasattr(obj, "_marimo_serialize_"):
- return obj._marimo_serialize_()
+ if serialize := getcallable(obj, "_marimo_serialize_"):
+ return serialize()
- if hasattr(obj, "_mime_"):
- mimetype, data = obj._mime_()
+ if mime := getcallable(obj, "_mime_"):
+ mimetype, data = mime()
return {"mimetype": mimetype, "data": data}
if isinstance(obj, range):
@@ -181,7 +182,9 @@ def enc_hook(obj: Any) -> Any:
)
# Handle objects with __slots__
- slots = getattr(obj, "__slots__", None)
+ # Check on type(obj) to avoid triggering __getattr__ on objects that
+ # implement it
+ slots = getattr(type(obj), "__slots__", None)
if slots is not None:
try:
slots = iter(slots)
diff --git a/marimo/_output/doc.py b/marimo/_output/doc.py
index 0c614e4d6c..c7242d4e6f 100644
--- a/marimo/_output/doc.py
+++ b/marimo/_output/doc.py
@@ -6,6 +6,7 @@ from typing import Any, Optional
from marimo._output.hypertext import Html
from marimo._output.md import md
from marimo._output.rich_help import mddoc
+from marimo._utils.methods import getcallable
@mddoc
@@ -22,11 +23,10 @@ def doc(obj: Any) -> Optional[Html]:
Documentation as an `Html` object if the object implements `RichHelp`;
otherwise, documentation is printed to console (and nothing is returned)
"""
- if hasattr(obj, "_rich_help_"):
- msg = obj._rich_help_()
+ if rich_help := getcallable(obj, "_rich_help_"):
+ msg = rich_help()
return (
md(msg) if msg is not None else md("No documentation available.")
)
- else:
- help(obj)
- return None
+ help(obj)
+ return None
diff --git a/marimo/_output/hypertext.py b/marimo/_output/hypertext.py
index 3215a69ec1..6cb1427607 100644
--- a/marimo/_output/hypertext.py
+++ b/marimo/_output/hypertext.py
@@ -11,6 +11,7 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.mime import MIME
from marimo._output.rich_help import mddoc
from marimo._output.utils import flatten_string
+from marimo._utils.methods import getcallable
if TYPE_CHECKING:
from collections.abc import Iterator
@@ -141,14 +142,14 @@ class Html(MIME):
return ("text/html", self.text)
# Try PNG representation first (for objects with _repr_png_)
- repr_png = getattr(self, "_repr_png_", None)
- if repr_png is not None and callable(repr_png):
+ repr_png = getcallable(self, "_repr_png_")
+ if repr_png is not None:
png_bytes = cast(bytes, repr_png())
return ("image/png", png_bytes.decode())
# Try markdown representation (for objects with _repr_markdown_)
- repr_markdown = getattr(self, "_repr_markdown_", None)
- if repr_markdown is not None and callable(repr_markdown):
+ repr_markdown = getcallable(self, "_repr_markdown_")
+ if repr_markdown is not None:
markdown_text = cast(str, repr_markdown())
return ("text/markdown", markdown_text)
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 0d405df59e..51f61c50b2 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -48,6 +48,7 @@ from marimo._plugins.validators import (
)
from marimo._runtime.functions import EmptyArgs, Function
from marimo._utils.memoize import memoize_last_value
+from marimo._utils.methods import getcallable
from marimo._utils.narwhals_utils import is_narwhals_lazyframe, make_lazy
from marimo._utils.parse_dataclass import parse_raw
@@ -234,8 +235,8 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
if is_non_interactive():
# Generates a plain HTML representation of the table data,
# useful for rendering in the GitHub viewer.
- repr_html = getattr(self._data, "_repr_html_", None)
- if repr_html is not None and callable(repr_html):
+ repr_html = getcallable(self._data, "_repr_html_")
+ if repr_html is not None:
return ("text/html", cast(str, repr_html()))
return ("text/html", str(self._data))
return ("text/html", self.text)
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index c5d3ba35c9..56c41b9398 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -66,6 +66,7 @@ from marimo._runtime.context.types import (
from marimo._runtime.context.utils import get_mode
from marimo._runtime.functions import EmptyArgs, Function
from marimo._utils.hashable import is_hashable
+from marimo._utils.methods import getcallable
from marimo._utils.narwhals_utils import (
can_narwhalify_lazyframe,
unwrap_narwhals_dataframe,
@@ -1484,8 +1485,8 @@ class table(
df = self.data
# Generates a plain HTML representation of the table data,
# useful for rendering in the GitHub viewer.
- repr_html = getattr(df, "_repr_html_", None)
- if repr_html is not None and callable(repr_html):
+ repr_html = getcallable(df, "_repr_html_")
+ if repr_html is not None:
return ("text/html", cast(str, repr_html()))
return ("text/html", str(df))
return ("text/html", self.text)
diff --git a/marimo/_utils/methods.py b/marimo/_utils/methods.py
index bb7275476e..2614cd86bf 100644
--- a/marimo/_utils/methods.py
+++ b/marimo/_utils/methods.py
@@ -3,10 +3,11 @@ from __future__ import annotations
import inspect
import types
-from typing import Any
+from typing import Any, Callable, cast
def is_callable_method(obj: Any, attr: str) -> bool:
+ """Check if an attribute is callable on an object."""
if not hasattr(obj, attr):
return False
@@ -14,3 +15,15 @@ def is_callable_method(obj: Any, attr: str) -> bool:
if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):
return False
return callable(method)
+
+
+def getcallable(obj: object, name: str) -> Callable[..., Any] | None:
+ """Get a callable attribute from an object, or None if not callable.
+
+ This safely handles objects that implement __getattr__ and return
+ non-callable values for any attribute name.
+ """
+ if (attr := getattr(obj, name, None)) is not None:
+ if callable(attr):
+ return cast(Callable[..., Any], attr)
+ return None
diff --git a/tests/_messaging/test_enc_hook.py b/tests/_messaging/test_enc_hook.py
index 170ed2072b..4be3a0ec98 100644
--- a/tests/_messaging/test_enc_hook.py
+++ b/tests/_messaging/test_enc_hook.py
@@ -66,6 +66,44 @@ def test_serialize_matplotlib_figure() -> None:
assert image_data["image/png"].startswith("data:image/png;base64,")
+def test_object_with_getattr_returning_non_callable() -> None:
+ """Test that objects implementing __getattr__ don't break serialization.
+
+ Some libraries (like rdflib.Namespace) implement __getattr__ to return
+ non-callable objects for any attribute name. This caused hasattr() to
+ return True for _marimo_serialize_ and _mime_, but calling them failed.
+
+ See: https://github.com/marimo-team/marimo/issues/8096
+ """
+
+ class NamespaceLike:
+ """Mimics rdflib.Namespace behavior."""
+
+ def __init__(self, base: str):
+ self.base = base
+
+ def __getattr__(self, name: str) -> str:
+ # Returns a string (non-callable) for any attribute
+ return f"{self.base}{name}"
+
+ ns = NamespaceLike("http://example.com/")
+
+ # Verify that hasattr returns True for special methods
+ assert hasattr(ns, "_marimo_serialize_")
+ assert hasattr(ns, "_mime_")
+
+ # But the attributes are not callable
+ assert not callable(ns._marimo_serialize_)
+ assert not callable(ns._mime_)
+
+ # enc_hook should handle this gracefully without raising TypeError
+ result = enc_hook(ns)
+
+ # Should fall through to __dict__ handling
+ assert isinstance(result, dict)
+ assert result["base"] == "http://example.com/"
+
+
def test_serialize_decimal() -> None:
decimal_obj = decimal.Decimal("123.45")
result = enc_hook(decimal_obj)
diff --git a/tests/_utils/test_methods.py b/tests/_utils/test_methods.py
new file mode 100644
index 0000000000..ea473e3582
--- /dev/null
+++ b/tests/_utils/test_methods.py
@@ -0,0 +1,71 @@
+# Copyright 2026 Marimo. All rights reserved.
+
+from marimo._utils.methods import getcallable, is_callable_method
+
+
+def test_getcallable() -> None:
+ """Test the getcallable utility function."""
+
+ class WithCallable:
+ def my_method(self) -> str:
+ return "called"
+
+ class WithNonCallable:
+ my_method = "not callable"
+
+ class WithGetattr:
+ def __getattr__(self, name: str) -> str:
+ return f"attr_{name}"
+
+ # Returns callable when attribute exists and is callable
+ obj_callable = WithCallable()
+ result = getcallable(obj_callable, "my_method")
+ assert result is not None
+ assert callable(result)
+ assert result() == "called"
+
+ # Returns None when attribute exists but is not callable
+ obj_non_callable = WithNonCallable()
+ result = getcallable(obj_non_callable, "my_method")
+ assert result is None
+
+ # Returns None when attribute doesn't exist
+ result = getcallable(obj_callable, "nonexistent")
+ assert result is None
+
+ # Returns None for objects with __getattr__ returning non-callable
+ obj_getattr = WithGetattr()
+ assert hasattr(obj_getattr, "any_attr") # hasattr returns True
+ result = getcallable(obj_getattr, "any_attr")
+ assert result is None
+
+
+def test_is_callable_method() -> None:
+ """Test the is_callable_method utility function."""
+
+ class WithMethod:
+ def my_method(self) -> str:
+ return "called"
+
+ class WithNonCallable:
+ my_attr = "not callable"
+
+ class WithGetattr:
+ def __getattr__(self, name: str) -> str:
+ return f"attr_{name}"
+
+ # Returns True when attribute exists and is callable
+ obj = WithMethod()
+ assert is_callable_method(obj, "my_method") is True
+
+ # Returns False when attribute exists but is not callable
+ obj_non_callable = WithNonCallable()
+ assert is_callable_method(obj_non_callable, "my_attr") is False
+
+ # Returns False when attribute doesn't exist
+ assert is_callable_method(obj, "nonexistent") is False
+
+ # Returns False for objects with __getattr__ returning non-callable
+ obj_getattr = WithGetattr()
+ assert hasattr(obj_getattr, "any_attr") # hasattr returns True
+ assert is_callable_method(obj_getattr, "any_attr") is False