Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions marimo/_plugins/core/json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,23 @@ def _convert_to_json(self, o: Any) -> Any:
}

# Handle objects with __slots__
if getattr(o, "__slots__", None):
# Reported error that sometimes poorly formed objects do get passed
# in.
assert isinstance(o.__slots__, (tuple, list)), (
f"Unexpected __slots__ type for {o.__class__.__name__}",
)
return {
slot: self._convert_to_json(getattr(o, slot))
for slot in o.__slots__ # type: ignore
if hasattr(o, slot)
}
if hasattr(o, "__slots__"):
slots = getattr(o, "__slots__", None)
if slots is not None:
# Reported error that sometimes poorly formed objects do get passed
# in.
try:
slots = iter(slots)
except TypeError as e:
raise TypeError(
"__slots__ expected to be tuple or list (or at least "
f"iterable), but got {type(slots)} for {type(o)}"
) from e
return {
slot: self._convert_to_json(getattr(o, slot))
for slot in slots
if hasattr(o, slot)
}

# Handle custom objects with __dict__
if hasattr(o, "__dict__"):
Expand Down
15 changes: 15 additions & 0 deletions tests/_plugins/core/test_json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,3 +438,18 @@ class InvalidClass: ...

encoded = json.dumps(invalid_obj, cls=WebComponentEncoder)
assert encoded == '{"__slots__": null}'


def test_empty_slots() -> None:
class ExClass:
__slots__ = []

# With a property (as sanity check)
@property
def one(self):
return 1

obj = ExClass()

encoded = json.dumps(obj, cls=WebComponentEncoder)
assert encoded == "{}"
Loading