如何从@cached_property装饰器清除缓存?

哈赞

我有一个称为“值”的函数,需要进行大量计算...

如果未更改标识符的数据集,则函数的结果始终相同。

数据集更改了某些标识符后,我想清除缓存,然后让函数再次进行计算。

通过查看以下代码,您可以更好地理解我:

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)
布莱克金

正如您在CPython源代码中所读到的那样cached_property,Python 3.8中a的值存储在同名的实例变量中。这没有记录,因此它可能是您不应该依赖的实现细节。

但是,如果您只是想在不考虑兼容性的情况下完成任务,则可以使用删除缓存del instance.value谁知道,也许当前的行为会在将来记录下来,所以在任何版本或解释器实现中都可以安全地使用它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章