简体   繁体   中英

How to call function in if statement and save return value

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM