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():
    # ...
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.