Decorator for a class method that caches return value after first access

Luke Taylor picture Luke Taylor · Apr 18, 2016 · Viewed 11.3k times · Source

My problem, and why

I'm trying to write a decorator for a class method, @cachedproperty. I want it to behave so that when the method is first called, the method is replaced with its return value. I also want it to behave like @property so that it doesn't need to be explicitly called. Basically, it should be indistinguishable from @property except that it's faster, because it only calculates the value once and then stores it. My idea is that this would not slow down instantiation like defining it in __init__ would. That's why I want to do this.

What I tried

First, I tried to override the fget method of the property, but it's read-only.

Next, I figured I'd try to implement a decorator that does needs to be called the first time but then caches the values. This isn't my final goal of a property-type decorator that never needs to be called, but I thought this would be a simpler problem to tackle first. In other words, this is a not-working solution to a slightly simpler problem.

I tried:

def cachedproperty(func):
    """ Used on methods to convert them to methods that replace themselves 
        with their return value once they are called. """
    def cache(*args):
        self = args[0] # Reference to the class who owns the method
        funcname = inspect.stack()[0][3] # Name of the function, so that it can be overridden.
        setattr(self, funcname, func()) # Replace the function with its value
        return func() # Return the result of the function
    return cache

However, this doesn't seem work. I tested this with:

>>> class Test:
...     @cachedproperty
...     def test(self):
...             print "Execute"
...             return "Return"
... 
>>> Test.test
<unbound method Test.cache>
>>> Test.test()

but I get an error about how the class didn't pass itself to the method:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method cache() must be called with Test instance as first argument (got nothing instead)

At this point, me and my limited knowledge of deep Python methods are very confused, and I have no idea where my code went wrong or how to fix it. (I've never tried to write a decorator before)

The question

How can I write a decorator that will return the result of calling a class method the first time it's accessed (like @property does), and be replaced with a cached value for all subsequent queries?

I hope this question isn't too confusing, I tried to explain it as well as I could.

Answer

00500005 picture 00500005 · Apr 18, 2016

If you don't mind alternative solutions, I'd recommend lru_cache

for example

from functools import lru_cache
class Test:
    @property
    @lru_cache(maxsize=None)
    def calc(self):
        print("Calculating")
        return 1

Expected output

In [2]: t = Test()

In [3]: t.calc
Calculating
Out[3]: 1

In [4]: t.calc
Out[4]: 1