Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack a tuple and assign a variable to the second value only if the first value is truthy

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():
    # ...
like image 881
Midhun Mathew Sunny Avatar asked Jan 25 '26 21:01

Midhun Mathew Sunny


1 Answers

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
like image 160
Alex Waygood Avatar answered Jan 28 '26 10:01

Alex Waygood