Home > other >  How do you interpret an assert statement if it contains an 'if .... else ....'?
How do you interpret an assert statement if it contains an 'if .... else ....'?

Time:11-14

I'm studying 'assert' statements in python and I don't understand the following sentence.

assert .. if ... else ... and ...

So if I understand correctly you have to use the above if you want to test an 'if else ' statement. You have to insert it right after the "if" statement the following: assert (P1 if E else P2) and E

For example

assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y

If understand assert y == builtins.max(x,y) It just checks if the condition is true or not and when it is not true it returns an assertion error. However in the case of : assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y

I have no clue what is happening. It apparently always returns true as well. But I cannot even guess what is exactly happening. I looked up what an assert statement does and the only thing it does is: assert <condition>,<error message> so check the condition and possibly return an error message. However I don't understand how ... if ... else ... and ... is a condition. I understand the and but how exactly do you interpret the if else part in that condition?

I don't really understand what I'm not understanding. It's probably very trivial. Hopefully someone can help me. Sorry for my spelling mistakes.

EDIT: its answered, I did not understand what a ternary operator is. For people from the future that have the similar question: https://book.pythontips.com/en/latest/ternary_operators.html

CodePudding user response:

What is going on here is the assertion of a ternary.

This:

(y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y

is conceptually:

A if cond else B # and cond2, but we'll come to that

Which evaluates first to A or B. We then assert that, so

assert A if cond else B

is the same as

x = A if cond else B
assert x

This particular ternary is not straightforward. It's equivalent to this:

if x < y:
    res = y == builtins.max(x, y)
else:
    res  = x == builtins.max(x,y)

assert res and x < y

IMHO it's rather unclear. It's funny anyhow, as in most contexts you can just do max() rather than builtins.max(). Perhaps it belongs in a test, or a context where max() has (unwisely) been overidden? [Thinking it through this is probably a test for builtins.max isn't it?]

References

For more information on python's ternary construction see e.g. this question.

  • Related