如何通过一个参数局部删除functools.lru_cache?

时间:2019-07-17 11:06:38

标签: python caching

我有一个get(bid, mid, pid)函数。它用lru_cache装饰。例如,我想删除所有带有bid == 105的缓存条目。

我在想一些闭包,它们返回装饰后的函数。然后,我为每个bid条目获得一些单独的缓存,并为非缓存函数提供了像路由器一样关闭的字典。但是也许有一种更Python化的方式呢?

upd:我想出了类似的东西,它似乎可以工作

getters = {}
def facade(bid, mid, pid):
    global getters             # not very good, better to use class

    if not bid in getters:
        def create_getter(bid):
            @functools.lru_cache(maxsize=None)
            def get(mid, pid):
                print ('cache miss')
                return bid + mid + pid
            return get
        getters[bid] = create_getter(bid)

    return getters[bid](mid, pid)

val = facade(bid, mid, pid)   # ability to read like before
if need_to_drop:
    getters[bid].cache_clear()  # ability to flush entries with specified bid

1 个答案:

答案 0 :(得分:0)

也许包装functools.lru_cache并过滤参数?

from functools import lru_cache


def filtered_lru(filter_func: callable, maxsize: int):
    def wrapper(f):
        cached = lru_cache(maxsize=maxsize)(f)

        def wrapped(*args, **kwargs):
            if filter_func(*args, **kwargs):
                print('Using cache')
                return cached(*args, **kwargs)
            else:
                print('Not using cache')
                return f(*args, **kwargs)

        return wrapped

    return wrapper


def _get_filter(*args, **kwargs):
    return args[0] != 0


@filtered_lru(_get_filter, maxsize=100)
def get(num):
    print('Calculating...')
    return 2 * num


if __name__ == '__main__':
    print(get(1))
    print(get(1))
    print(get(1))
    print(get(0))
    print(get(0))

输出:

Using cache
Calculating...
2
Using cache
2
Using cache
2
Not using cache
Calculating...
0
Not using cache
Calculating...
0