littleali
littleali

Reputation: 408

Evaluate a function one time and store the result in python

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

Upvotes: 0

Views: 278

Answers (2)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

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()

Upvotes: 0

Dave
Dave

Reputation: 1874

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

Upvotes: 0

Related Questions