How can I make @functools.lru_cache
decorator ignore some of the function arguments with regard to caching key?
For example, I have a function that looks like this:
def find_object(db_handle, query):
# (omitted code)
return result
If I apply lru_cache
decorator just like that, db_handle
will be included in the cache key. As a result, if I try to call the function with the same query
, but different db_handle
, it will be executed again, which I'd like to avoid. I want lru_cache
to consider query
argument only.
With cachetools you can write:
You will need to install cachetools (
pip install cachetools
).The syntax is:
Here is another example that includes keyword args:
In the example above note that the lambda function input args match the
my_func
args. You don't have to exactly match the argspec if you don't need to. For example, you can use kwargs to squash out things that aren't needed in the hashkey:In the above example we don't care about
d=
,e=
andf=
args when looking up a cache value, so we can squash them all out with **kwargs.