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

Viewed 34884

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.

4 Answers

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.

Related