You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cachetools是否支持unless功能?Python缓存入门遇问题

用cachetools实现条件缓存(跳过特定场景的缓存)

cachetools的@cached装饰器本身没有内置你期望的unless参数,但可以通过以下两种方式实现「执行代码后根据变量值决定是否缓存」的逻辑:

方法1:手动操作缓存对象

直接在函数内部判断条件,若不需要缓存则移除当前调用对应的缓存条目:

from cachetools import cached, TTLCache, keys

# 提前实例化缓存对象
cache = TTLCache(maxsize=64, ttl=300)

@cached(cache=cache)
def retrieve_values(input_val):
    # 业务逻辑:计算结果和判断变量
    my_value = False  # 这里替换成你的实际判断逻辑
    result = 'testValue'
    
    # 当my_value为False时,移除当前调用的缓存记录
    if not my_value:
        # 生成当前函数调用对应的缓存键(和@cached内部生成逻辑一致)
        cache_key = keys.hashkey(input_val)
        cache.pop(cache_key, None)  # pop时加None避免键不存在报错
    
    return result

方法2:自定义带unless逻辑的装饰器

如果需要在多个函数复用这个逻辑,可以封装一个自定义装饰器:

from cachetools import cached, TTLCache, keys

def cached_unless(cache, unless_func):
    def decorator(func):
        # 先用cachetools的cached装饰原函数
        cached_func = cached(cache)(func)
        
        def wrapper(*args, **kwargs):
            # 先执行原函数,获取结果和判断条件
            # 注意:这里需要原函数返回结果+判断变量,或者通过其他方式传递判断条件
            result, my_value = func(*args, **kwargs)
            
            # 调用unless_func判断是否要缓存
            if not unless_func(my_value):
                cache_key = keys.hashkey(*args, **kwargs)
                cache.pop(cache_key, None)
            
            return result
        return wrapper
    return decorator

# 使用示例
cache = TTLCache(maxsize=64, ttl=300)

# 定义判断函数:返回True则缓存,False则不缓存
def should_cache(my_value):
    return my_value

@cached_unless(cache=cache, unless_func=should_cache)
def retrieve_values(input_val):
    my_value = False  # 替换为你的实际逻辑
    return 'testValue', my_value

# 调用时可以拆包获取结果
final_result, _ = retrieve_values("your_input")

两种方法说明

  • 方法1实现简单,适合单个函数快速修改,不需要改动函数返回值;
  • 方法2更灵活,适合多个函数复用条件缓存逻辑,但需要调整函数返回值(或通过非局部变量传递判断条件)。

内容的提问来源于stack exchange,提问作者user1807815

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:47:26