M. T.
M. T.

Reputation: 396

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:

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?

Upvotes: 0

Views: 1466

Answers (1)

Tom Lubenow
Tom Lubenow

Reputation: 1161

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

Upvotes: 4

Related Questions