Skip to content

Commit

Permalink
Fixes #41 keygen works with omitted kwargs
Browse files Browse the repository at this point in the history
  • Loading branch information
cevans87 committed Jan 21, 2020
1 parent ef5ba0a commit 1b05caf
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
11 changes: 7 additions & 4 deletions atools/_memoize_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,14 @@ def table_name(self) -> str:

def default_keygen(self, *args, **kwargs) -> Tuple[Hashable, ...]:
"""Returns all params (args, kwargs, and missing default kwargs) for function as kwargs."""

return tuple(self.get_args_as_kwargs(*args, **kwargs).values())

def get_args_as_kwargs(self, *args, **kwargs) -> Mapping[str, Any]:
args_as_kwargs = {}
for k, v in zip(self.default_kwargs, args):
args_as_kwargs[k] = v

return tuple(ChainMap(args_as_kwargs, kwargs, self.default_kwargs).values())
return ChainMap(args_as_kwargs, kwargs, self.default_kwargs)

def get_memo(self, key: Union[int, str]) -> _Memo:
try:
Expand Down Expand Up @@ -221,7 +224,7 @@ async def get_key(self, *args, **kwargs) -> Union[int, str]:
if self.keygen is None:
key = self.default_keygen(*args, **kwargs)
else:
key = self.keygen(*args, **kwargs)
key = self.keygen(**self.get_args_as_kwargs(*args, **kwargs))
if isinstance(key, tuple):
key = list(key)
else:
Expand Down Expand Up @@ -277,7 +280,7 @@ def get_key(self, *args, **kwargs) -> Union[int, str]:
if self.keygen is None:
key = self.default_keygen(*args, **kwargs)
else:
key = self.keygen(*args, **kwargs)
key = self.keygen(**self.get_args_as_kwargs(*args, **kwargs))

key = self.get_hashed_key(key)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

setup(
name='atools',
version='0.10.4',
version='0.10.5',
packages=find_packages(),
python_requires='>=3.6',
url='https://github.com/cevans87/atools',
Expand Down
8 changes: 8 additions & 0 deletions test/test_memoize_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,3 +919,11 @@ def _foo() -> None:
del foo
# FIXME there's a race condition here. Garbage collector may not have cleaned up foo yet
assert r() is None


def test_keygen_works_with_default_kwargs() -> None:
@memoize(keygen=lambda bar: bar)
def foo(bar=1) -> None:
...

foo()

0 comments on commit 1b05caf

Please sign in to comment.