pythonstatic-methodsevaluation-strategy

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

Solution

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