From 4432b14ffbaaee0aa7142b694c853d518671bb88 Mon Sep 17 00:00:00 2001 From: Mohamad Kanj Date: Tue, 27 Aug 2024 04:32:20 +0200 Subject: [PATCH] fix(cache): support for unpassed default args (#39) * 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 --- redis_cache/__init__.py | 6 +++++- tests/test_redis_cache.py | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/redis_cache/__init__.py b/redis_cache/__init__.py index 7c0448e..899d6de 100644 --- a/redis_cache/__init__.py +++ b/redis_cache/__init__.py @@ -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) @@ -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 diff --git a/tests/test_redis_cache.py b/tests/test_redis_cache.py index 76b5616..7a6bf47 100644 --- a/tests/test_redis_cache.py +++ b/tests/test_redis_cache.py @@ -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) @@ -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