Evaluate a function one time and store the result in python

257 Views Asked by At

I wrote a static method in python which takes time to compute but I want it to compute just one time and after that return the computed value. What should I do ? here is a sample code :

class Foo:
    @staticmethod
    def compute_result():
         #some time taking process 

Foo.compute_result() # this may take some time to compute but store results
Foo.compute_result() # this method call just return the computed result
2

There are 2 best solutions below

0
On BEST ANSWER
def evaluate_result():
    print 'evaluate_result'
    return 1

class Foo:
    @staticmethod
    def compute_result():
        if not hasattr(Foo, '__compute_result'):
            Foo.__compute_result = evaluate_result()
        return Foo.__compute_result 

Foo.compute_result()
Foo.compute_result()
0
On

I think what you want to do is called memoizing. There are several ways to do it with decorators, one of them is using functools (Python 3) or some short handwritten code if you only care for hashable types (also for Python 2).

You can annotate multiple decorators for one method.

@a
@b
def f():
   pass