U
U
un1t2017-03-20 12:32:10
Django
un1t, 2017-03-20 12:32:10

How is cached_property invalidated?

Junga has a decorator that allows you to turn a method into a property and cache it.
More precisely, judging by the code, the result of the method execution at the first call turns into an attribute of the object with the same name.

class cached_property(object):
    """
    Decorator that converts a method with a single self argument into a
    property cached on the instance.

    Optional ``name`` argument allows you to make cached properties of other
    methods. (e.g.  url = cached_property(get_absolute_url, name='url') )
    """
    def __init__(self, func, name=None):
        self.func = func
        self.__doc__ = getattr(func, '__doc__')
        self.name = name or func.__name__

    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.__dict__[self.name] = self.func(instance)
        return res

To invalidate the cache in the documentation, you need to use del. And it really does work. It's just not clear how it works. After all, the __delete__ method is not defined.
del person.friends # or delattr(person, "friends")

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iLq, 2020-02-18
@iLq

cached_property inherits from object which has a __delattr__ method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question