pensfute
pensfute

Reputation: 351

clear cache of @property methods python

I have some property methods in a Class and I want to clear the cache of this property at some point.

Example :

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

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

if I do self.prop.clear_cache(), here the error message I get :

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

clear_cache() works for functions but not for property methods. Is there any way to do that?

Upvotes: 9

Views: 6499

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122132

You need to access the cache attributes on the getter attribute of the property object, so .fget. You can only access the property object on the class:

Test.prop.fget.cache_clear()

That's because the @property decorator replaced the prop function object with LRU cache, with a property instance.

Accessing the property name on an instance will always give you the result of the property getter, not the function object with cache controls.

Demo:

>>> 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

Note that using a LRU cache this way means the cache storage is shared across all instances of the class, with separate results stored per instance (the cache is keyed on the self parameter). Clearing the cache will clear it for all instances. Given the default maxsize=128 configuration, that means that only the property value for the most recently-used 128 instances will be cached. Access the property on instance #129 and then again an instance #1 will mean that the value is re-calculated for #1 as that instance's property value will have been evicted.

Upvotes: 19

Related Questions