3

I have a Python function which returns a tuple with a boolean and string

def check_something():
    # ...
    return bool_value, str_messsage 

Is there a way I can use the output of this function in an if statement using the boolean and assign the string value to a variable in the if statement

if not check_something():
    # ...
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Midhun Mathew Sunny
  • 1,271
  • 4
  • 17
  • 30

1 Answers1

17
if (result := check_something())[0]:
    var = result[1]

This uses the 'walrus operator', which is new syntax that was introduced in Python 3.8. You can read about it here.

For Python <= 3.7, you have to include one extra line:

bool_val, str_message = check_something()
if bool_val:
    var = str_message
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46