如何使@functools.lru_cache装饰器忽略有关缓存键的某些函数参数?
@functools.lru_cache
例如,我有一个看起来像这样的函数:
def find_object(db_handle, query): # (omitted code) return result
如果我lru_cache像这样应用装饰器,db_handle它将包含在缓存键中。结果,如果我尝试使用相同query但不同的函数调用该函数db_handle,它将再次执行,这是我想避免的。我只想lru_cache考虑query论点。
lru_cache
db_handle
query
使用cachetools可以编写:
from cachetools import cached from cachetools.keys import hashkey from random import randint @cached(cache={}, key=lambda db_handle, query: hashkey(query)) def find_object(db_handle, query): print("processing {0}".format(query)) return query queries = list(range(5)) queries.extend(range(5)) for q in queries: print("result: {0}".format(find_object(randint(0, 1000), q)))