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.

Improve cache for anywidget: (#5879)

David Angaritac4ea360de7db
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index 3f6f6b8310..221b2498cb 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -5,7 +5,7 @@ import hashlib
import weakref
from copy import deepcopy
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar
import marimo._output.data.data as mo_data
from marimo import _loggers
@@ -23,24 +23,47 @@ if TYPE_CHECKING:
AnyWidget,
)
+
LOGGER = _loggers.marimo_logger()
+K = TypeVar("K")
+V = TypeVar("V")
+
+
+class WeakCache(Generic[K, V]):
+ """A WeakCache "watches" the key and removes its entry if the key is destroyed."""
+
+ def __init__(self) -> None:
+ self._data: dict[int, V] = {}
+ self._finalizers: dict[int, weakref.finalize[[int], K]] = {}
+
+ def add(self, k: K, v: V) -> None:
+ oid: int = id(k) # finalize will be called before id is reused
+ self._data[oid] = v
+ self._finalizers[oid] = weakref.finalize(k, self._cleanup, oid)
+
+ def get(self, k: K) -> V | None:
+ return self._data.get(id(k))
+
+ def __len__(self) -> int:
+ return len(self._data)
+
+ def _cleanup(self, oid: int) -> None:
+ self._data.pop(oid, None)
+ self._finalizers.pop(oid, None)
+
# Weak dictionary
# When the widget is deleted, the UIElement will be deleted as well
-cache: dict[Any, UIElement[Any, Any]] = weakref.WeakKeyDictionary() # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
+_cache: WeakCache[AnyWidget, UIElement[Any, Any]] = WeakCache() # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
def from_anywidget(widget: AnyWidget) -> UIElement[Any, Any]:
"""Create a UIElement from an AnyWidget."""
- try:
- if widget not in cache:
- cache[widget] = anywidget(widget) # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
- return cache[widget]
- except TypeError as e:
- # Unhashable widgets can't be used as keys in a WeakKeyDictionary
- LOGGER.warning(e)
- return anywidget(widget)
+ if not (el := _cache.get(widget)):
+ el = anywidget(widget)
+ _cache.add(widget, el) # type: ignore[no-untyped-call, unused-ignore, assignment] # noqa: E501
+ return el
T = dict[str, Any]
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index bc4502658c..de44c5f7fa 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -1,12 +1,19 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import gc
+import weakref
from hashlib import md5
import pytest
from marimo._dependencies.dependencies import DependencyManager
-from marimo._plugins.ui._impl.from_anywidget import anywidget, from_anywidget
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._plugins.ui._impl.from_anywidget import (
+ WeakCache,
+ anywidget,
+ from_anywidget,
+)
from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -405,8 +412,57 @@ x = as_marimo_element.count
# This should work without errors despite the widget being unhashable
widget = UnhashableWidget()
+ assert not isinstance(widget, UIElement)
+
+ wrapped = from_anywidget(widget)
+
+ assert isinstance(wrapped, UIElement)
+ assert wrapped is from_anywidget(widget)
+
+ @staticmethod
+ def test_hashable_widget() -> None:
+ class HashableWidget(_anywidget.AnyWidget):
+ _esm = ""
+
+ widget = HashableWidget()
+ assert not isinstance(widget, UIElement)
+
wrapped = from_anywidget(widget)
- assert wrapped is not None
+
+ assert isinstance(wrapped, UIElement)
+ assert wrapped is from_anywidget(widget)
+
+ @staticmethod
+ def test_WeakCache() -> None:
+ class TestWidget:
+ pass
+
+ class TestWrapper:
+ def __init__(self, obj):
+ self.obj = weakref.ref(obj)
+
+ widget1 = TestWidget()
+ widget2 = TestWidget()
+ wrapped1 = TestWrapper(widget1)
+ wrapped2 = TestWrapper(widget2)
+
+ _cache: WeakCache[TestWidget, TestWrapper] = WeakCache()
+
+ assert _cache.get(widget1) is None
+ assert _cache.get(widget2) is None
+ assert _cache.get(TestWidget()) is None
+
+ _cache.add(widget1, wrapped1)
+ _cache.add(widget2, wrapped2)
+
+ assert _cache.get(widget1) is wrapped1
+ assert _cache.get(widget2) is wrapped2
+
+ old_len = len(_cache)
+ del widget1
+ gc.collect()
+
+ assert len(_cache) == old_len - 1
@staticmethod
async def test_partial_state_updates() -> None: