这是我的情况,is_exist
函数有性能问题。
def is_exist(link :str) -> bool:
if query_db(link) is True:
return True
return False
def process(link: str)
if is_exist(link) is True:
return
# do something
# put result to database
LRU 缓存是一个很好的解决方案,但是经过几个小时的努力我发现 lru_cache 不满足我的要求。我想要这样的:
def is_exist(link :str) -> bool:
if query_db(link) is True:
return True
return False
def process(link: str)
if lru_cache.query(link) is True:
return
if is_exist(link) is True:
lru_cache.add(link)
return
# do something
# put result to database
functiontools 中的 LRU Cache 是一个装饰器。它没有查询方法。如果我使用 @lru_cache
装饰 is_exist
,则当 is_exist
返回 false 时,某些链接将被重复处理。
PS:将结果放入数据库是异步的
最佳答案
functools.lru_cache
仅缓存结果,但不缓存异常。这意味着函数应该在任何情况下引发异常,并且稍后必须重新评估该异常。
@lru_cache
def is_exist(link: str) -> bool:
if query_db(link):
return True # added to cache
raise LookupError # ignored by cache
这允许客户端功能使用缓存进行检查,但仍然插入丢失的条目。
def process(link: str)
try:
is_exist(link)
except LookupError:
# do something
# put result to database
关于python - 为什么 python3 lru_cache 不提供 put 和 query 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68663883/