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

查看:32
本文介绍了使@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天全站免登陆