4

I would like to dynamically set the maxsize of python lru_cache, but when I wrap a function (A._get) in antoher function (A.get), the cache doesn't work. The original use of lru_cache (A._get2) works properly.

from functools import partial, lru_cache, wraps

lru_cache_maxsize = 5

class A:
    @staticmethod
    def _get(func_name: str, date: str, **params):
        time.sleep(1)
        return func_name, date, params

    @staticmethod
    def get(func_name: str, date: str, **params):
        maxsize = params.pop("maxsize", lru_cache_maxsize)
        # print(maxsize)
        return lru_cache(maxsize=maxsize)(A._get)(func_name, date, **params)

    @staticmethod
    @lru_cache(maxsize=5)
    def _get2(func_name: str, date: str, **params):
        time.sleep(1)
        return func_name, date, params

method 1 (Not working)

for i in range(10):
    for n in range(5):
        ret = A.get("func1", str(n))
        print(ret)

method 2 (This works, but I want to dynamically set the maxsize)

for i in range(10):
    for n in range(5):
        ret = A._get2("func1", str(n))
        print(ret)

[update]:

I found the asnwers, and posted the links below.

disable `functools.lru_cache` from inside function

Python functools lru_cache with instance methods: release object

Pythons lru_cache on inner function doesn't seem to work

wuya
  • 85
  • 1
  • 6

0 Answers0