pydanny/cached-property

Invalidating cache from within object does not work

Make42 opened this issue · 1 comments

It seems to me that resetting the cache from within my object (which uses the cached_property) does not work. I am getting the error KeyError: 'trans1':

class MyClass:

    def __init__(self, parameter):
        self.parameter = parameter

    def fit(self, data):
        print('fit')
        self.intermediate_data_ = data + self.parameter + 2
        del self.__dict__['trans1']
        del self.__dict__['trans2']
        return self
    
    @cached_property
    def trans1(self):
        print('trans 1 - calc')
        return self.intermediate_data_ / self.parameter / 2

    @cached_property
    def trans2(self):
        print('trans 2 - calc')
        return self.intermediate_data_ / self.parameter / 5
    del self.__dict__['trans1']
    del self.__dict__['trans2']

needs to be replaced with

        for f in ['trans1', 'trans2']:
            self.__dict__.pop(f, None)

because 'trans1' and 'trans2' do not exist in self.__dict__ during the first call to fit. The methods 'trans1' and 'trans2' are in MyClass.__dict__ instead. After running one of the methods, e.g. 'trans1', the respective instance's 'trans1' overshadows the classes 'trans1'-method.