5

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))
pygeek
  • 7,356
  • 1
  • 20
  • 41
JUH
  • 71
  • 4

3 Answers3

3

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]
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
  • I'd rather add a function call that does `assert cond, msg` and call it like `validate(*check_numbers(1,2))` – Verthais Aug 02 '22 at 14:49
1

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))
halfer
  • 19,824
  • 17
  • 99
  • 186
Markus Dutschke
  • 9,341
  • 4
  • 63
  • 58
-1
assert test_numbers(1,2)[0]

Tuples can be indexed because they are iterables.

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

cisco.prog
  • 49
  • 4