Skip to content

Add feature: call with freshness threshold #262

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/cachier/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from functools import wraps
from functools import partial, wraps
from typing import Any, Optional, Union
from warnings import warn

Expand Down Expand Up @@ -214,8 +214,7 @@ def cachier(
def _cachier_decorator(func):
core.set_func(func)

@wraps(func)
def func_wrapper(*args, **kwds):
def _call(max_age: timedelta, *args, **kwds):
nonlocal allow_none
_allow_none = _update_with_defaults(allow_none, "allow_none", kwds)
# print('Inside general wrapper for {}.'.format(func.__name__))
Expand Down Expand Up @@ -260,7 +259,7 @@ def func_wrapper(*args, **kwds):
if _allow_none or entry.value is not None:
_print("Cached result found.")
now = datetime.now()
if now - entry.time <= _stale_after:
if now - entry.time <= min(_stale_after, max_age):
_print("And it is fresh!")
return entry.value
_print("But it is stale... :(")
Expand Down Expand Up @@ -294,6 +293,8 @@ def func_wrapper(*args, **kwds):
_print("No entry found. No current calc. Calling like a boss.")
return _calc_entry(core, key, func, args, kwds)

func_wrapper = wraps(func)(partial(_call, timedelta.max))

def _clear_cache():
"""Clear the cache."""
core.clear_cache()
Expand Down Expand Up @@ -321,10 +322,16 @@ def _precache_value(*args, value_to_cache, **kwds): # noqa: D417
)
return core.precache_value((), kwargs, value_to_cache)

def _caller_with_freshness_threshold(max_age: timedelta):
return wraps(func)(partial(_call, max_age))

func_wrapper.clear_cache = _clear_cache
func_wrapper.clear_being_calculated = _clear_being_calculated
func_wrapper.cache_dpath = _cache_dpath
func_wrapper.precache_value = _precache_value
func_wrapper.caller_with_freshness_threshold = (
_caller_with_freshness_threshold
)
return func_wrapper

return _cachier_decorator
27 changes: 27 additions & 0 deletions tests/test_call_with_freshness_threshold.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import time
from datetime import timedelta

import cachier


def test_call_with_freshness_threshold():
@cachier.cachier()
def test_func(a, b):
print("Computing...")
return a + b

print(f"{test_func(1, 2) = }")
print(f"{test_func(1, 2) = }")
caller_with_freshness_threshold = (
test_func.caller_with_freshness_threshold(
timedelta(seconds=0.5),
)
)
print(f"{caller_with_freshness_threshold(1, 2) = }")
print(f"{time.sleep(1.0) = }")
print(f"{test_func(1, 2) = }")
print(f"{caller_with_freshness_threshold(1, 2) = }")


if __name__ == "__main__":
test_call_with_freshness_threshold()
Loading