JUH
JUH

Reputation: 71

How to unpack Tuple containing bool and str for assert

Is there a way to unpack a tuple containing boolean and custom message and apply assert on it in single line single statement?

def test_numbers(a,b):
    if a==b:
        return True,"Are Equal"
    return False, "Not equal"

res, st = test_numbers(1,2)
assert res,st

Then tried the following, which didn’t work

assert *test_numbers(1,2)

same for:

assert (*test_numbers(1,2))

Upvotes: 5

Views: 623

Answers (3)

Markus Dutschke
Markus Dutschke

Reputation: 10606

One can go the detour over a custom assert function, but there should be a nicer way.

At least this solution gives the generated error message and is not called, when optimization (-> __debug__ == False) is on.

def check_numbers(a,b):
    if a==b:
        return True,"Are Equal"
    return False, "Not equal"

def custom_assert(cond, msg):
    # https: // docs.python.org / 3 / reference / simple_stmts.html  # the-assert-statement
    if __debug__:
        if not cond: raise AssertionError(msg)

if __name__ == "__main__":
    custom_assert(*check_numbers(1, 2))

Upvotes: 1

Markus Dutschke
Markus Dutschke

Reputation: 10606

Solved by Walrus operator for python >= 3.8

https://realpython.com/python-walrus-operator/ Finally, this issue can be settled. The walrus operators := purpose is exactly to avoid double computation.

def check_numbers(a,b):
    if a==b:
        return True,"Are Equal"
    return False, "Not equal"

if __name__ == "__main__":
    assert (res:=check_numbers(1, 2))[0], res[1]

Upvotes: 3

cisco.prog
cisco.prog

Reputation: 49

assert test_numbers(1,2)[0]

Tuples can be indexed because they are iterables.

You don't need the 2nd value, do you ?

Upvotes: -1

Related Questions