I'm stuck in a simple question that I can't find an answer. If want to call a function in an if statement. This is a function really challenging and it takes a long time to get response, how can I preserve the return value?
I explain the problem with an example:
def recursive:
if .... :
return value
else:
return False
recursive is an hypothetically function that takes a lot of time to generating response, that could be a value or just a simple boolean False.
...
if recursive():
...value? (make something with value return)
other method
...
if recursive():
value = recursive()
This other method will call the function 2 times and it takes too long time.
How can I solve this?
答案 0 :(得分:3)
Python 3.8 will add an operator to do exactly this (called the walrus operator :=
), but unfortunately the closest thing you can do today is this
value = recursive()
if value:
pass # do stuff with value
else:
pass # do other stuff with value
# can still do stuff with value here
If running on 3.8+, the following will be valid
if value := recursive():
pass # do stuff with value
else:
pass # do other stuff with value
# can still do stuff with value here