本地开发时如何禁用Python functools的@lru_cache装饰器?
解决functools.lru_cache根据配置禁用的问题
lru_cache确实没有disable参数,你没遗漏什么。要实现根据配置开关缓存,常用这几种接地气的方法:
方法一:自定义条件装饰器
写个包装装饰器,根据配置决定是否启用lru_cache:
from functools import lru_cache, wraps def conditional_cache(enable_cache): def decorator(func): if enable_cache: return lru_cache(maxsize=None)(func) else: # 不启用缓存时,直接返回原函数(用wraps保留原函数元信息) @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return decorator # 用法:开发模式下禁用缓存,生产模式启用 @conditional_cache(enable_cache=not settings.development_mode) def your_function(arg1, arg2): # 函数逻辑 return arg1 + arg2
方法二:动态选择装饰器
根据配置提前定义要用的装饰器,直接替换:
from functools import lru_cache # 根据开发模式切换装饰器 if settings.development_mode: # 空装饰器,直接返回原函数 def no_op_cache(func): return func cache_decorator = no_op_cache else: # 生产模式用正常的lru_cache cache_decorator = lru_cache(maxsize=None) # 直接使用定义好的装饰器 @cache_decorator def your_function(arg1, arg2): return arg1 + arg2
额外提示:清空缓存而非禁用
如果你只是需要在开发时清空已缓存的数据,而非完全禁用缓存,可以调用函数的cache_clear()方法,比如在服务启动时或者每次调试前执行:
your_function.cache_clear()
但这只是清空现有缓存,新的调用仍会被缓存,不如前面两种方法能彻底禁用缓存逻辑。
内容的提问来源于stack exchange,提问作者Kulu
相关产品推荐
相关产品推荐

