使@lru_cache忽略某些函数参数 [英] Make @lru_cache ignore some of the function arguments

查看:144
本文介绍了使@lru_cache忽略某些函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使 @functools.lru_cache 装饰器忽略某些内容关于缓存密钥的函数参数?

How can I make @functools.lru_cache decorator ignore some of the function arguments with regard to caching key?

例如,我有一个看起来像这样的函数:

For example, I have a function that looks like this:

def find_object(db_handle, query):
    # (omitted code)
    return result

如果我像这样应用lru_cache装饰器,则db_handle将包含在缓存键中.结果,如果我尝试使用相同的query但不同的db_handle调用该函数,它将再次执行,这是我想避免的.我希望lru_cache仅考虑query参数.

If I apply lru_cache decorator just like that, db_handle will be included in the cache key. As a result, if I try to call the function with the same query, but different db_handle, it will be executed again, which I'd like to avoid. I want lru_cache to consider query argument only.

推荐答案

使用 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)))

这篇关于使@lru_cache忽略某些函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆