How to call function in if statement and save return value

时间:2019-04-16 22:46:08

标签: python function if-statement

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:

  • function
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.

  • main
...

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?

1 个答案:

答案 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