2

I have a function like this:

def shippable_lines(api_object,data_dict):
....

this function can be effectively cached by examining two of the keys in data_dict.

api_object is irrelevant.

I don't want to change the signature of the function.

This Make @lru_cache ignore some of the function arguments answers a similar question, but by introducing a new module: https://pypi.org/project/cachetools/

is there a way of doing this with pure lru_cache?

EDIT It is actually so easy to do with cachetools: this is a requirement specifically identified:

from cachetools import LRUCache, cached

shippable_lines_cache = LRUCache(maxsize=4096)

def shippable_lines_key(dear_cached_api, dear_sale: dict):
    return f"{dear_sale['ID']}-{dear_sale['LastModifiedOn']}"


@cached(shippable_lines_cache, key=shippable_lines_key)
def shippable_lines(dear_cached_api, dear_sale: dict) -> List[dict]:
        ...
Tim Richardson
  • 6,608
  • 6
  • 44
  • 71
  • I guess you have to copy paste the code from the stdlib and add the functionality you want https://github.com/python/cpython/blob/1fe79a43400d092a074c6f9ae5eb290ea3e4f281/Lib/functools.py#L530 – Boris Verkhovskiy Nov 17 '19 at 08:09
  • Maybe you can override the `make_key` function of the `lru_cache_wrapper` object. https://github.com/python/cpython/blob/1fe79a43400d092a074c6f9ae5eb290ea3e4f281/Lib/functools.py#L533 – Boris Verkhovskiy Nov 17 '19 at 08:12

0 Answers0