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

Memoize with defaulted parameters #264

Open
sbrandtb opened this issue Sep 9, 2022 · 1 comment
Open

Memoize with defaulted parameters #264

sbrandtb opened this issue Sep 9, 2022 · 1 comment

Comments

@sbrandtb
Copy link

sbrandtb commented Sep 9, 2022

More a design question, at least first: When using memoize(), default arguments are not taken into account:

@CACHE.memoize()
def f(a, b = 'foo'):
    pass

When calling f(1), only 1 as args will be taken into the cache key, not b='foo', see code. As long as the default does not change, that is OK, but when it does, the cache key for the function call that does not pass b does not change.

It sounds like a weird edge condition, but I ran into this because I used b = generate_cache_key_from_things_that_are_static_at_runtime() and found out much later that cache invalidation via different results of that function did not work.

I believe that it would totally be possible to take default values for parameters into account, i.e. via introspect. Do you think this would be an antipattern, or even more confusing, or worth implementing?

By the way, my solution to this looks like following and is arguably a cleaner implementation anyways:

from functools import cache

@cache
def generate_cache_key_from_things_that_are_static_at_runtime():
    ...

def f(a):
    return f_cached(a, generate_cache_key_from_things_that_are_static_at_runtime())

@CACHE.memoize()
def f_cached(a, b):
    ...
@grantjenks
Copy link
Owner

Looks worth implementing but I don’t think the functools.lru_cache version does so. Memoize is modeled after the standard library pattern so it would be good to know why they did not do so.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants