'How can I have my function called again after storing its result in a variable, each time the variable is accessed?

I have a concept where I store values returned by functions in variables which makes it easier for me.

But I am having the problem that the value in the variable isn't dynamically calling the function each time. So it returns the same value all the time.

I have made a code snip to illustrate it in a easy way:

def value():
    resp = requests.get('http://www.google.com').elapsed.total_seconds()
    return resp

test = value()

while True:
    print test
    time.sleep(10)

Output:

0.00649
0.00649

In this case, in the while true when I print test, it returns the same value, even though I am calling the function value(). How can I solve this issue? I know I can put the function in the while loop, but I want to have it as a variable.



Solution 1:[1]

test = value() isn't storing the function it's storing the results. You should just call value() in your loop or if you want to assign the function it would be test = value and then test() in your loop.

Solution 2:[2]

test = value() calls the function and stores the return value. It does not store the function. test = value would store the function, but the you need to print test() in order to call it.

def value():
        resp = requests.get('http://www.google.com').elapsed.total_seconds()
        return resp

test = value

while True:
        print test()
        time.sleep(10)

Solution 3:[3]

You can change your code like this..

def value():
    resp = requests.get('http://www.google.com').elapsed.total_seconds()
    return resp

test = value()

while True:
    print test
    time.sleep(10)

change this line

test = value

to

test = value()

Now means you are storing your function in a variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AlG
Solution 2 cdarke
Solution 3 Saqib