Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear the cache from @cached_property decorator?

Tags:

python

I have an function called "value" that makes heavy calculation...

The result of the function is always the same if the dataset is not changed for the identifier.

Once the dataset is changed for some identifier, I want to clear the cache, and let the function calculate it again.

You can better understand me by looking at this code:

from functools import cached_property


class Test:
    identifiers = {}
    dataset = an empty object of dataset type

    def __init__(self, identifier, ...)
        self.identifier = identifier
        ...
        Test.identifiers[identifier] = self

    ...

    @cached_property
    def value(self):
        result = None
        # heavy calculate based on dataset
        return result

    @classmethod
    def get(cls, identifier):
        if identifier in cls.identifiers:
            return cls.identifiers[identifier]
        else:
            return cls(identifier, ...)

    @classmethod
    def update(cls, dataset):
        for block in dataset:
            # assume there is block['identifier'] in each block
            # here i want to clear the cache of value() function
            instance = cls.get(block['identifier'])
            # clear @cached_property of instance
            cls.dataset.append(block)
like image 382
Hazan Avatar asked Jun 30 '20 17:06

Hazan


People also ask

What is cached property decorator in Python?

The @cached_property is a decorator which transforms a method of a class into a property whose value is computed only once and then cached as a normal attribute.

Does Python have property cache?

cached_property is a decorator that converts a class method into a property whose value is calculated once and then cached like a regular attribute. The cached value will be available until the object or the instance of the class is destroyed.

How do you use the cache function in Python?

Memoization allows you to optimize a Python function by caching its output based on the parameters you supply to it. Once you memoize a function, it will only compute its output once for each set of parameters you call it with. Every call after the first will be quickly retrieved from a cache.


1 Answers

As you can read in the CPython source, the value for a cached_property in Python 3.8 is stored in an instance variable of the same name. This is not documented, so it may be an implementation detail that you should not rely upon.

But if you just want to get it done without regards to compatibility, you can remove the cache with del instance.value. And who knows, maybe the current behavior will be documented in the future, so it will be safe to use it in any version or interpreter implementation.

like image 162
Blckknght Avatar answered Nov 15 '22 13:11

Blckknght