Home > database >  Expression with commas in assert
Expression with commas in assert

Time:04-13

What does comma do in this line of Python code? Is it correct?

assert (response_data['data']['name'] == 'pl1', response_data['data']['status'] == 'active', response_data['data']['version'] == 1)

CodePudding user response:

What does comma do in this line of Python code?

(response_data['data']['name'] == 'pl1', response_data['data']['status'] == 'active', response_data['data']['version'] == 1)

is 3-tuple

Is it correct?

assert does consider truth-iness of provided expression, every non-emtpy tuple is True, therefore you will never get AssertionError due to this line.

You might use all if you want AssertionError if one or more conditions does not hold

assert all((response_data['data']['name'] == 'pl1', response_data['data']['status'] == 'active', response_data['data']['version'] == 1))

CodePudding user response:

Well, I think it's not what you want to achieve. In such case assert evaluates the whole expression in the parentheses, which is just a tuple: (bool, bool, bool). And since this tuple is not empty (it has three elements), it will be always evaluated to True. Just as not empty string or not empty list.

If you want to check all these conditions, do it separately (or maybe by using all()).

  • Related