From f8e73825e8d7ca285fac5987f6c3842f5a7448d7 Mon Sep 17 00:00:00 2001 From: Frithjof Gressmann Date: Fri, 6 Dec 2024 00:19:49 -0600 Subject: [PATCH] Include defaults in cachable key --- CHANGELOG.md | 1 + src/machinable/interface.py | 9 ++++++++- tests/test_interface.py | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8990933e..d0b418c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ # Unreleased - Support sqlean.py +- Include defaults in cachable key # v4.10.5 diff --git a/src/machinable/interface.py b/src/machinable/interface.py index 8f398bd2..40bf9443 100644 --- a/src/machinable/interface.py +++ b/src/machinable/interface.py @@ -53,8 +53,15 @@ def _wrapper(self, *args, **kwargs): if not self.cached(): return fn(self, *args, **kwargs) try: + sig = inspect.signature(fn) + bound_args = sig.bind(self, *args, **kwargs) + bound_args.apply_defaults() key = object_hash( - {"fn": fn.__name__, "args": args, "kwargs": kwargs} + { + "fn": fn.__name__, + "args": bound_args.args[1:], + "kwargs": bound_args.kwargs, + } )[:8] except TypeError as _ex: if fail_mode == "raise": diff --git a/tests/test_interface.py b/tests/test_interface.py index 5be11390..021da57b 100644 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -440,6 +440,20 @@ def test3(self, a=0, k="test"): assert c.test3(k=slice(1)) == 700 assert c.test3(k=slice(1)) == 800 + # default-args + class C(Component): + @cachable() + def test(self, payload="default", a=1): + return getattr(self, "latent", "test") + + c = C().launch() + assert c.test(a=1) == "test" + c.latent = "changed" + assert c.test(a=1) == "test" + assert c.test(payload="default", a=1) == "test" + assert c.test(payload="default") == "test" + assert c.test(a=2) == "changed" + def test_interface_update(tmp_storage): i = get("machinable.interface", {"a": 1}).commit()