Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cache result of function then get new result python

so in python, I have a function foo that takes several seconds to execute and returns a value, I have another function bar that calls foo and then runs some code on the result, this is slowing down my code as it can take several seconds to execute foo.

def foo():
    #do some processing
    return 'something'

def bar():
    x=foo()
    #do some processing on x to generate y
    return y

how do I make it so that bar uses the value of foo from last time it was called, and then runs foo in the background and saves that value for next time foo is called?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One of simple solution could be run foo in Thread and make it store result in some global variable.

x = None
def foo():
    global x
    # do some processing
    x = "something"
foo() # call it first time to get first x result

def bar():
    # y = x if you want to make sure it doesn't change durign bar run 
    t = Thread(target=foo)
    t.start()
    # you can use x here
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading