views:

59

answers:

2

Here are four simple invocations of assert:

>>> assert 1==2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError

>>> assert 1==2, "hi"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError: hi

>>> assert(1==2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AssertionError

>>> assert(1==2, "hi")

Note that the last one does not raise an error. What is the difference between calling assert with or without parenthesis that causes this behavior? My practice is to use parenthesis, but the above suggests that I should not.

+5  A: 

The last assert would have given you a warning (SyntaxWarning: assertion is always true, perhaps remove parentheses?) if you ran it through a full interpreter, not through IDLE. Because assert is a keyword and not a function, you are actually passing in a tuple as the first argument and leaving off the second argument.

Recall that non-empty tuples evaluate to True, and since the assertion message is optional, you've essentially called assert True when you wrote assert(1==2, "hi").

Mark Rushakoff
The reason is doesn't happen for `assert (1==2)` is parentheses around a single expression won't create a tuple automatically; you'd get the same behavior as #4 if you did `assert (1==2,)`. The same thing would happen if you did `print ('foo', 'bar')` instead of `print 'foo', 'bar'`; you'd see the tuple outputted
Michael Mrozek
It's worth further emphasizing that statements of the form `assert(test, message)` probably wrong, and certainly confusing. No parens!
tcarobruce
+1  A: 

assert 1==2, "hi" is parsed as assert 1==2, "hi" with "hi" as the second parameter for the keyword. Hence why it properly gives an error.

assert(1==2) is parsed as assert (1==2) which is identical to assert 1==2, because parens around a single item don't create a tuple unless there's a trailing comma e.g. (1==2,).

assert(1==2, "hi") is parsed as assert (1==2, "hi"), which doesn't give an error because a non-empty tuple (False, "hi") isn't a false value, and there is no second parameter supplied to the keyword.

You shouldn't use parentheses because assert is not a function in Python - it's a keyword.

Amber
@Amber: Your first assertion is incorrect: the assert statement takes two parameters, the second being optional. From the Language Reference: `assert_stmt ::= "assert" expression ["," expression]`. The remainder of your answer is right-on however.
Don O'Donnell
Right, fixed. :)
Amber