清除@property方法python的缓存

问题描述 投票:2回答:1

我在类中有一些属性方法,我想在某个时候清除此属性的缓存。

示例:

class Test():
    def __init__(self):
        pass

    @property
    @functools.lru_cache()
    def prop(self):
        # Compute some stuffs and return complex number

如果我做self.prop.clear_cache(),这里得到的错误信息:

AttributeError: 'numpy.complex128' object has no attribute 'cache_clear'

clear_cache()适用于函数,但不适用于属性方法。有没有办法做到这一点?

python python-3.x
1个回答
4
投票

您需要访问属性对象的getter属性的缓存属性,因此.fget。您只能访问该类的属性对象:

Test.prop.fget.cache_clear()

那是因为@property装饰器用一个属性实例用LRU缓存替换了prop函数对象。

访问实例上的属性名称将始终为您提供属性getter的结果,而不是具有缓存控件的函数对象。

演示:

>>> import functools
>>> class Foo:
...     @property
...     @functools.lru_cache()
...     def bar(self):
...         print("Accessing the bar property")
...         return 42
...
>>> f = Foo()
>>> f.bar
Accessing the bar property
42
>>> f.bar  # cached
42
>>> Foo.bar.fget.cache_clear()
>>> f.bar
Accessing the bar property
42

请注意,以这种方式使用LRU缓存意味着缓存存储在所有类的实例之间共享,每个实例存储单独的结果(缓存是在self参数上键入的)。清除缓存将清除所有实例。给定默认的maxsize=128配置,这意味着只缓存最近使用的128个实例的属性值。访问实例#129上的属性,然后实例#1将意味着为#1重新计算该值,因为该实例的属性值将被驱逐。

© www.soinside.com 2019 - 2024. All rights reserved.