Search code examples
python-3.xclasscachingpropertiesfunctools

lru_cache that saves for all class instances


Is there any way I can lru_cache a @property at class level in python so that even when returning that calculated property with the same values for another class instance, the property will not be recalculated, rather pulled from cache. I want to achieve something like the below:

class SomeClass:
    def __init__(self, num1, num2):
         self.num1 = num1
         self.num2 = num2

    @property
    @lru_cache
    def sum(self):  #this can even be a class method if needed, I don't really care
       return self.num1 + self.num2


    t1 = SomeClass(2,3)
    t1.sum
    >> 5          #calculating


    t2 = SomeClass(2,3)
    t2.sum
    >> 5          #returning cache from t1, NOT calculating

Solution

  • A solution using methodtools.lru_cache

    from methodtools import lru_cache
    
    called = 0
    
    class SomeClass:
        def __init__(self, num1, num2):
            self.num1 = num1
            self.num2 = num2
    
        @lru_cache()
        @classmethod
        def _sum(cls, num1, num2):
            global called
            called += 1
            return num1 + num2
    
        @property
        def sum(self):
            return self._sum(self.num1, self.num2)
    
    
    if __name__ == '__main__':
        assert called == 0
    
        t1 = SomeClass(2, 3)
        print(t1.sum)
        assert called == 1
    
        t2 = SomeClass(2, 3)
        print(t2.sum)
        assert called == 1