Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stacking cache_this decorators #50

Open
thorwhalen opened this issue Sep 20, 2024 · 0 comments
Open

Stacking cache_this decorators #50

thorwhalen opened this issue Sep 20, 2024 · 0 comments

Comments

@thorwhalen
Copy link
Member

Consider this code:

from dol import cache_this

trace = []
cache = dict()
disk = dict()

class A:

    @cache_this(cache=disk)
    def f(self):
        trace.append('In f method')
        return 42
    
a = A()

assert a.f == 42
assert trace == ['In f method']  # proof that the method was called 
assert disk['f'] == 42  # proof that the result was cached in disk
assert a.f == 42  # access the attribute again
assert trace == ['In f method']  # proof that the method was NOT called again

It would be convenient to be able to stack caches like this (this doesn't work):

class A:
    @cache_this(cache=cache)
    @cache_this(cache=disk)
    def f(self):
        trace.append('In f method')
        return 42

so that the net effect would be to save the output of f in both disk and cache, but read from cache only (when it's there), and if disk already has an f, to read from disk (but write to cache).

What is needed is probably the ability for cache_this to see what it's wrapping, and if it's already a CachedProperty, it should wrap the wrapped method of it. Essentially, getting to this (which works):

from dol import cache_this, CascadedStores
from collections import ChainMap

trace = []
cache = dict()
disk = dict(g=8)

cascade_cache_this = cache_this(cache=CascadedStores([cache, disk]))

class A:

    @cascade_cache_this
    def f(self):
        trace.append('In f method')
        return 42
    
    @cascade_cache_this
    def g(self):
        trace.append('In g method')
    
a = A()

assert a.f == 42
assert trace == ['In f method']  # proof that the method was called 
assert cache['f'] == 42  # proof that the result was cached in chached_a
assert disk['f'] == 42  # proof that the result was cached in chached_b
assert a.f == 42  # access the attribute again
assert trace == ['In f method']  # proof that the f method was NOT called again

assert a.g == 8
assert trace == ['In f method']  # proof that the g method was NEVER called (it got the value from disk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant