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
fix: Enable cache decoration on class methods (#5630)
Dylan Madisetti470f0c608ceb
diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex e64cf1b31d..19d152f82a 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -63,23 +63,44 @@ UNEXPECTED_FAILURE_BOILERPLATE = (if TYPE_CHECKING:from types import FrameType, TracebackType- from marimo._runtime.dataflow import DirectedGraphfrom marimo._save.stores import Storeclass _cache_call:- """Like functools.cache but notebook-aware. See `cache` docstring`"""+ """Like functools.cache but notebook-aware. See `cache` docstring"""++ __slots__ = (+ "base_block",+ "scope",+ "scoped_refs",+ "pin_modules",+ "hash_type",+ "_args",+ "_var_arg",+ "_var_kwarg",+ "_loader",+ "_loader_partial",+ "_bound",+ "_last_hash",+ "_frame_offset",+ "__wrapped__",+ )- graph: DirectedGraph- cell_id: str- module: ast.Module+ base_block: BlockHasher+ scope: dict[str, Any]+ scoped_refs: set[str]+ pin_modules: bool+ hash_type: str_args: list[str]- _var_arg: Optional[str] = None- _var_kwarg: Optional[str] = None- _loader: Optional[State[Loader]] = None+ _var_arg: Optional[str]+ _var_kwarg: Optional[str]+ _loader: Optional[State[Loader]]_loader_partial: LoaderPartial- name: str- fn: Optional[Callable[..., Any]]+ _bound: Optional[dict[str, Any]]+ _last_hash: Optional[str]+ _frame_offset: int+ # Consistent with functools.cache+ __wrapped__: Optional[Callable[..., Any]]def __init__(self,@@ -96,9 +117,13 @@ class _cache_call:self.hash_type = hash_typeself._frame_offset = frame_offsetself._loader_partial = loader_partial- self._last_hash: Optional[str] = None+ self._last_hash = None+ self._var_arg = None+ self._var_kwarg = None+ self._loader = None+ self._bound = {}if _fn is None:- self.fn = None+ self.__wrapped__ = Noneelse:self._set_context(_fn)@@ -117,7 +142,7 @@ class _cache_call:f"{UNEXPECTED_FAILURE_BOILERPLATE}")- self.fn = fn+ self.__wrapped__ = fnsig = inspect.signature(fn)self._args = [param.name@@ -178,7 +203,7 @@ class _cache_call:graph = ctx.graphcell_id = ctx.cell_id or ctx.execution_context.cell_id- module = strip_function(self.fn)+ module = strip_function(self.__wrapped__)self.base_block = BlockHasher(module=module,@@ -192,7 +217,7 @@ class _cache_call:)# Load global cache from state- name = self.fn.__name__+ name = self.__wrapped__.__name__# Note, that if the function name shadows a global variable, the# lifetime of the cache will be tied to the global variable.# We can invalidate that by making an invalid namespace.@@ -206,9 +231,51 @@ class _cache_call:assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATEreturn self._loader()+ def __get__(+ self, instance: Any, _owner: Optional[type] = None+ ) -> _cache_call:+ """__get__ is invoked on instance access;+ e.g. `obj.fn` (__get__ called on `fn`)+ `instance` is the specific object, while owner is `type(instance)`.++ We check if `bound` is unset as a recursion guard, then create a new+ instance of _cache_call, copying over the inspection data we have+ already computed. We notably do not memoize since copying is cheap-+ additionally updating the parent itself would make the object+ unpicklable.+ """+ if instance is not None and not bool(self._bound):+ if not callable(self.__wrapped__):+ raise TypeError(+ f"cache() expected a callable, got {type(self.__wrapped__)} "+ "(have you wrapped a function?)"+ )+ # Bind to the instance+ copy = _cache_call(+ None,+ self._loader_partial,+ pin_modules=self.pin_modules,+ hash_type=self.hash_type,+ )+ # Manually set context, since we have lost frame context.+ # Safe to not copy because data is RO.+ copy.__wrapped__ = functools.partial(self.__wrapped__, instance)+ copy._var_arg = self._var_arg+ copy._var_kwarg = self._var_kwarg+ copy._loader = self._loader+ copy.base_block = self.base_block+ copy.scope = self.scope+ copy.scoped_refs = self.scoped_refs+ # Except _args, which is is different.+ copy._args = self._args.copy()+ # Remove the first arg, which is 'self' or otherwise bound.+ copy._bound = {f"{ARG_PREFIX}{copy._args.pop(0)}": instance}+ return copy+ return self+def __call__(self, *args: Any, **kwargs: Any) -> Any:# Capture the deferred call case- if self.fn is None:+ if self.__wrapped__ is None:if len(args) != 1:raise TypeError("cache() takes at most 1 argument (expecting function)"@@ -236,6 +303,7 @@ class _cache_call:**ctx.globals,**arg_dict,**kwargs_copy,+ **(self._bound or {}),}assert self._loader is not None, UNEXPECTED_FAILURE_BOILERPLATEattempt = content_cache_attempt_from_base(@@ -253,7 +321,7 @@ class _cache_call:if attempt.hit:attempt.restore(scope)return attempt.meta["return"]- response = self.fn(*args, **kwargs)+ response = self.__wrapped__(*args, **kwargs)# stateful variables may be globalscope = {k: v for k, v in scope.items() if k in attempt.stateful_refsdiff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 8d5c646b3a..9c883dea5c 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -1295,6 +1295,150 @@ class TestCacheDecorator:# Verify cache hitsassert k.globals["pos_only_func"].hits == 1+ async def test_cache_decorator_method_wrap(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.save import cache++ class MyClass:+ def __init__(self, x):+ self.x = x+ @cache+ def method(self, y):+ return self.x + y++ case_a = MyClass(0).method+ case_b = MyClass(1).method+ case_c = MyClass(1).method+ result1 = case_a(2)+ hash1 = case_a._last_hash+ result2 = case_b(2)+ hash2 = case_b._last_hash+ result3 = case_c(2)+ hash3 = case_c._last_hash++ base_hash = MyClass.method._last_hash++ obj = MyClass(0)+ # __get__ is called in both places.+ # Sanity check the functor returned.+ get_method_0 = obj.method+ get_method_1 = obj.method+ """+ ),+ ]+ )++ assert not k.stdout.messages, k.stdout.messages+ assert not k.stderr.messages, k.stderr.messages++ # Verify results+ assert k.globals["result1"] == 2 # 0 + 2+ assert k.globals["result2"] == 3 # 1 + 2+ assert k.globals["result3"] == 3 # 1 + 2+ assert k.globals["hash1"] != k.globals["hash2"]+ assert k.globals["hash2"] == k.globals["hash3"]+ # Since self.loader is shared, the lookup dict is shared.+ assert k.globals["case_a"].hits == 1+ assert k.globals["case_b"].hits == 1+ assert k.globals["case_c"].hits == 1+ assert k.globals["base_hash"] is None++ # Not per say correct or incorrect; but known, documented behavior.+ assert k.globals["get_method_0"] != k.globals["get_method_1"]++ async def test_cache_static_decorator_method_wrap(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.save import cache++ class MyClass:++ @staticmethod+ @cache+ def static_method(x, y):+ return x + y+++ case_a = MyClass().static_method+ case_b = MyClass().static_method+ case_c = MyClass.static_method+ result1 = case_a(1, 2)+ hash1 = case_a._last_hash+ result2 = case_b(2, 1)+ hash2 = case_b._last_hash+ result3 = case_c(1, 2)+ hash3 = case_c._last_hash+ base_hash = MyClass.static_method._last_hash+ """+ ),+ ]+ )+ assert not k.stdout.messages, k.stdout.messages+ assert not k.stderr.messages, k.stderr.messages++ # Verify results+ assert k.globals["result1"] == 3+ assert k.globals["result2"] == 3+ assert k.globals["result3"] == 3+ assert k.globals["hash1"] != k.globals["hash2"]+ assert k.globals["hash1"] == k.globals["hash3"]+ assert k.globals["base_hash"] is not None++ async def test_cache_class_decorator_method_wrap(+ self, k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await k.run(+ [+ exec_req.get(+ """+ from marimo._save.save import cache++ class MyClass:+ @classmethod+ @cache+ def class_method(cls, x, y):+ return x + y+ case_a = MyClass().class_method+ case_b = MyClass().class_method+ case_c = MyClass.class_method+ result1 = case_a(1, 2)+ hash1 = case_a._last_hash+ result2 = case_b(2, 1)+ hash2 = case_b._last_hash+ result3 = case_c(1, 2)+ hash3 = case_c._last_hash+ base_hash = MyClass.class_method._last_hash+ """+ ),+ ]+ )+ assert not k.stdout.messages, k.stdout.messages+ assert not k.stderr.messages, k.stderr.messages++ # Verify results+ assert k.globals["result1"] == 3+ assert k.globals["result2"] == 3+ assert k.globals["result3"] == 3+ assert k.globals["hash1"] != k.globals["hash2"]+ assert k.globals["hash1"] == k.globals["hash3"]+ assert k.globals["case_c"]._last_hash is not None++ # NB. base_hash has different behavior than the others on python 3.13++ # 3.13 has base_hash == hash1, while <3.13 has base_hash != None+ if sys.version_info >= (3, 13):+ assert k.globals["base_hash"] == k.globals["hash1"]+ else:+ assert k.globals["base_hash"] is None+async def test_cross_cell_cache(self, k: Kernel, exec_req: ExecReqProvider) -> None: