我如何在 python @functools.lru_cache 上使用 cache_clear() [英] How do I use cache_clear() on python @functools.lru_cache

查看:40
本文介绍了我如何在 python @functools.lru_cache 上使用 cache_clear()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档指出:

<块引用>

装饰器还提供了一个 cache_clear() 函数用于清除或使缓存无效.

它没有提供关于如何使用 cache_clear()

的任何示例或指导

我有两个问题:

  • 如何从不同的函数运行 cache_clear()?
  • 如果我有条件地将 cache_clear() 调用放入正在缓存的函数中,它会被执行吗?

解决方案

除了缓存之外,lru_cache 装饰器还添加了新的函数,对被装饰的函数 - cache_info>cache_clear.下面是一个简单的例子,可以解释它们是如何工作的:

<预><代码>>>>@lru_cache(5)...定义 foo():... print('正在执行 foo...')...>>>富()执行 foo...>>>富()>>>foo.cache_info()缓存信息(命中=1,未命中=1,最大大小=5,当前大小=1)>>>foo.cache_clear()>>>富()执行 foo...

回答您的问题:

<块引用>

如果我在被缓存的函数中有条件地调用 cache_clear() ,它会被执行吗?

如果结果尚未缓存,该函数将执行并根据您的条件执行cache_clear.不过我不会使用这样的解决方案 - 一个好的做法是在缓存对象之外无效,否则在最坏的情况下你根本不会有无效的风险,在最好的情况下是不可读的代码.

<块引用>

如何从不同的函数运行 cache_clear()?

只需导入缓存函数并调用 cache_clear 即可:

from x import foo定义栏():foo.cache_clear()

The documentation states:

The decorator also provides a cache_clear() function for clearing or invalidating the cache.

It doesn't provide any examples or guidance on how to use cache_clear()

I have two questions:

  • How can I run cache_clear() from a different function?
  • If I put a cache_clear() call conditionally inside the function that is being cached, will it ever get executed?

解决方案

Besides caching, lru_cache decorator also adds new functions, to the decorated function - cache_info and cache_clear. Below is a simple example that should explain how they work:

>>> @lru_cache(5)
... def foo():
...     print('Executing foo...')
... 
>>> foo()
Executing foo...
>>> foo()
>>> foo.cache_info()
CacheInfo(hits=1, misses=1, maxsize=5, currsize=1)
>>> foo.cache_clear()
>>> foo()
Executing foo...

Answering your questions:

If I put a cache_clear() call conditionally inside the function that is being cached, will it ever get executed?

If the result is not cached already, the function will execute and based on your conditions, it should execute cache_clear. I wouldn't use such solution though - a good practise is to invalidate outside the cached object, otherwise you risk no invalidation at all in worst cases, unreadable code in best case.

How can I run cache_clear() from a different function?

Just import cached function and call cache_clear on it:

from x import foo

def bar():
    foo.cache_clear()

这篇关于我如何在 python @functools.lru_cache 上使用 cache_clear()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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