lrnv
lrnv

Reputation: 1106

python cached_property : how to delete?

Consider the following system of cached and deleting properties from a class :

class cached_property(object):
    """
    Descriptor (non-data) for building an attribute on-demand on first use.
    """

    def __init__(self, factory):
        """
        <factory> is called such: factory(instance) to build the attribute.
        """
        self._attr_name = factory.__name__
        self._factory = factory

    def __get__(self, instance, owner):
        # Build the attribute.
        attr = self._factory(instance)

        # Cache the value; hide ourselves.
        setattr(instance, self._attr_name, attr)

        return attr


class test():

    def __init__(self):
        self.kikou = 10

    @cached_property
    def caching(self):
        print("computed once!")
        return True

    def clear_cache(self):
        try: del self.caching
        except: pass

b = test()
print(b.caching)
b.clear_cache()

Is it the right way to delete this cached property ? I am not shure of the way i did it..

Upvotes: 7

Views: 9362

Answers (1)

voodooattack
voodooattack

Reputation: 1176

Your code will try to delete the method itself, and not the cached value. The correct way to do it is to delete the key from self.__dict__ (which is where the data is actually stored).

Here's an example taken from something I'm currently working on:

def Transform:
    ...

    @cached_property
    def matrix(self):
        mat = Matrix44.identity()
        mat *= Matrix44.from_translation(self._translation)
        mat *= self._orientation
        mat *= Matrix44.from_scale(self._scale)
        return mat

    @property
    def translation(self):
        return self._translation

    @translation.setter
    def translation(self, value: Vector3):
        self._translation = value
        if "matrix" in self.__dict__:
            del self.__dict__["matrix"]

Upvotes: 8

Related Questions