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

Added param to add custom key generator function #10

Merged
merged 2 commits into from
Nov 3, 2018
Merged
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
9 changes: 7 additions & 2 deletions src/cache_memoize/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ def cache_memoize(
args_rewrite=None,
hit_callable=None,
miss_callable=None,
key_generator_callable=None,
store_result=True,
cache_alias=DEFAULT_CACHE_ALIAS,
):
Expand All @@ -25,6 +26,7 @@ def cache_memoize(
re-represent them for the sake of the cache key.
:arg function hit_callable: Gets executed if key was in cache.
:arg function miss_callable: Gets executed if key was *not* in cache.
:arg key_generator_callable: Custom cache key name generator.
:arg bool store_result: If you know the result is not important, just
that the cache blocked it from running repeatedly, set this to False.
:arg string cache_alias: The cache alias to use; defaults to 'default'.
Expand Down Expand Up @@ -81,7 +83,7 @@ def callmeonce(arg1):
def noop(*args):
return args
args_rewrite = noop

cache = caches[cache_alias]

def decorator(func):
Expand All @@ -98,7 +100,10 @@ def _make_cache_key(*args, **kwargs):
@wraps(func)
def inner(*args, **kwargs):
refresh = kwargs.pop('_refresh', False)
cache_key = _make_cache_key(*args, **kwargs)
if key_generator_callable is None:
cache_key = _make_cache_key(*args, **kwargs)
else:
cache_key = key_generator_callable(*args, **kwargs)
if refresh:
result = None
else:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_cache_memoize.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,23 @@ def runmeonce(a):
assert len(calls_made) == 2
runmeonce_locmem(10)
assert len(calls_made) == 2


def test_cache_memoize_works_with_custom_key_generator():

calls_made = []

def key_generator(*args):
key = (':{}' * len(args)).format(*args)
return 'custom_namespace:{}'.format(key)

@cache_memoize(10, key_generator_callable=key_generator)
def runmeonce(arg1, arg2):
calls_made.append((arg1, arg2))
return arg1 + 1

runmeonce(1, 2)
runmeonce(1, 2)
assert len(calls_made) == 1
runmeonce(1, 3)
assert len(calls_made) == 2