python 装饰器实现缓存,每个实例的Python LRU缓存装饰器

from lru_cache import lru_cache

class Test:

@lru_cache(maxsize=16)

def cached_method(self, x):

return x + 5

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.

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?

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值