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

memoize Allow to bypass cache by value #334

Open
kraktus opened this issue Oct 14, 2024 · 0 comments
Open

memoize Allow to bypass cache by value #334

kraktus opened this issue Oct 14, 2024 · 0 comments

Comments

@kraktus
Copy link

kraktus commented Oct 14, 2024

Hello, thanks for the lib.

It'd be useful to have a callback parameter in memoize that would define whether we want to cache it or not.
The callback could be to define inclusion of exclusion of the cache, I'm agnostic on it (probably would make sense to have it exclude, since we want to cache by default?)

I could make the PR if interested, in the meantime if someone is looking for an user-implementation, here's the one that was enough for my need.

import diskcache
import functools

from typing import Callable, Any

cache = diskcache.Cache()

from typing import Callable, Any, cast

def diskcache_only_if[T](cache_if: Callable[[T], bool], expire: int) -> Callable[[Callable[..., T]], Callable[..., T]]:
    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> T:
            memoized_func = cache.memoize(expire=expire)(func)
            res = cast(T, memoized_func(*args, **kwargs))
            if not cache_if(res):
                key = memoized_func.__cache_key__(*args, **kwargs) # type: ignore
                del cache[key]
            return res
        return wrapper
    return decorator

def test_diskcache_only_if():
    cache.clear()
    global cached
    cached = True
    cache_if: Callable[[int], bool] = lambda x: x > 1
    @diskcache_only_if(cache_if, expire=100)
    def test(x: int) -> int:
        global cached
        cached = False
        return x + 1

    assert test(1) == 2
    assert not cached
    cached = True
    assert test(1) == 2
    assert cached
    assert test(0) == 1
    assert not cached
    cached = True
    assert test(0) == 1
    assert not cached

test_diskcache_only_if()
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