Skip to content

Commit

Permalink
fix(cache): support for unpassed default args (#39)
Browse files Browse the repository at this point in the history
* feat(cache): support caching functions with positional-only arguments

BREAKING CHANGE: requires Python version >= 3.8

* fix(cache): cache params with defaults not passed as args

---------

Co-authored-by: Taylor Hakes <[email protected]>
  • Loading branch information
mhmdkanj and taylorhakes authored Aug 27, 2024
1 parent e701a9e commit 4432b14
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion redis_cache/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import wraps
from json import dumps, loads
from base64 import b64encode
from inspect import signature
from inspect import signature, Parameter

def compact_dump(value):
return dumps(value, separators=(',', ':'), sort_keys=True)
Expand Down Expand Up @@ -44,6 +44,10 @@ def get_args(fn, args, kwargs):
parsed_args[vkwargs_name] = {}
parsed_args[vkwargs_name][key] = value

for param in arg_sig.parameters.values():
if param.name not in parsed_args and param.default is not Parameter.empty:
parsed_args[param.name] = param.default

return parsed_args


Expand Down
4 changes: 4 additions & 0 deletions tests/test_redis_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,9 @@ def fn5(*, d, **e):
def fn6(a, b, /, c, d):
pass

def fn7(a, b, c=3, *, d):
pass

assert get_args(fn1, (1,2), {}) == dict(a=1, b=2)
assert get_args(fn1, [], dict(a=1, b=2)) == dict(a=1, b=2)
assert get_args(fn1, [1], dict(b=2)) == dict(a=1, b=2)
Expand All @@ -373,6 +376,7 @@ def fn6(a, b, /, c, d):
assert get_args(fn4, [1, 2, 3, 4], dict(d=5, f=6, g=7, h=8)) == dict(a=1, c=[2, 3, 4], d=5, e=dict(f=6, g=7, h=8))
assert get_args(fn5, [], dict(d=5, f=6, g=7, h=8)) == dict(d=5, e=dict(f=6, g=7, h=8))
assert get_args(fn6, [1, 2, 3], dict(d=4)) == dict(a=1, b=2, c=3, d=4)
assert get_args(fn7, [1, 2], dict(d=4)) == dict(a=1, b=2, c=3, d=4)

# Simulate the environment where redis is not available
# Only test the CacheDecorator since the exception handling should be done inside the decorator
Expand Down

0 comments on commit 4432b14

Please sign in to comment.