每个实例的Python LRU缓存装饰器 [英] Python LRU Cache Decorator Per Instance

查看:288
本文介绍了每个实例的Python LRU缓存装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用在这里找到的LRU Cache装饰器: http://code. activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/

Using the LRU Cache decorator found here: http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/

from lru_cache import lru_cache
class Test:
    @lru_cache(maxsize=16)
    def cached_method(self, x):
         return x + 5

我可以用它创建一个修饰的类方法,但最终会创建一个全局缓存,该全局缓存适用于Test类的所有实例.但是,我的目的是创建每个实例缓存.因此,如果要实例化3个测试,我将拥有3个LRU缓存,而不是所有3个实例的1个LRU缓存.

I can create a decorated class method with this but it ends up creating a global cache that applies to all instances of class Test. However, my intent was to create a per instance cache. So if I were to instantiate 3 Tests, I would have 3 LRU caches rather than 1 LRU cache that for all 3 instances.

我唯一有发生这种情况的指示是在不同的类实例修饰方法上调用cache_info()时,它们都返回相同的高速缓存统计信息(如果它们与非常不同的参数进行交互,则极不可能发生) ):

The only indication I have that this is happening is when calling the cache_info() on the different class instances decorated methods, they all return the same cache statistics (which is extremely unlikely to occur given they are being interacted with very different arguments):

CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)
CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)
CacheInfo(hits=8379, misses=759, maxsize=128, currsize=128)

是否有一个装饰器或技巧可以使我轻松地使该装饰器为每个类实例创建一个缓存?

Is there a decorator or trick that would allow me to easily cause this decorator to create a cache for each class instance?

推荐答案

假设您不想修改代码(例如,因为您只想移植到3.3并使用stdlib functools32 ,而不是将配方复制并粘贴到您的代码中),有一个显而易见的解决方案:为每个实例创建一个新的装饰实例方法.

Assuming you don't want to modify the code (e.g., because you want to be able to just port to 3.3 and use the stdlib functools.lru_cache, or use functools32 out of PyPI instead of copying and pasting a recipe into your code), there's one obvious solution: Create a new decorated instance method with each instance.

class Test:
    def cached_method(self, x):
         return x + 5
    def __init__(self):
         self.cached_method = lru_cache(maxsize=16)(self.cached_method)

这篇关于每个实例的Python LRU缓存装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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