python assert with and without parenthesis

PythonAssertParentheses

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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").

Solution 2 - Python

If you put the parenthesis in there because you wanted a multi-line assert, then an alternative is to put a backslash at the end of the line like this:

foo = 7
assert foo == 8, \
    "derp should be 8, it is " + str(foo)

Prints:

AssertionError: "derp should be 8, it is 7

Why does this python assert have to be different from everything else:

I think the pythonic ideology is that a program should self-correct without having to worry about the special flag to turn on asserts. The temptation to turn off asserts is too great, and thus it's being deprecated.

I share your annoyance that the python assert has unique syntax relative to all other python programming constructs, and this syntax has yet again changed from python2 to python3 and again changed from python 3.4 to 3.6. Making assert statements not backward compatible from any version to any other version.

It's a tap on the shoulder that assert is a 3rd class citizen, it will be totally removed in python4, and certainly again in Python 8.1.

Solution 3 - Python

You can break assert statement without \ like this:

foo = 7
assert foo == 8, (
    'derp should be 8, it is ' + str(foo))

Or if you have even longer message:

foo = 7
assert foo == 8, (
    'Lorem Ipsum is simply dummy text of the printing and typesetting '
    'industry. Lorem Ipsum has been the industry\'s standard dummy text '
    'ever since the 1500s'
)

Solution 4 - Python

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.

Solution 5 - Python

Following is cited from the python doc

>Assert statements are a convenient way to insert debugging assertions into a program:

>assert_stmt ::= "assert" expression ["," expression]

The simple form, assert expression, is equivalent to

if __debug__:
    if not expression: raise AssertionError

The extended form, assert expression1, expression2, is equivalent to

if __debug__:
    if not expression1: raise AssertionError(expression2)

So when you're using parenthesis here, you're using the simple form, and the expression is evaluated as a tuple, which is always True when being casted to bool

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongaefanView Question on Stackoverflow
Solution 1 - PythonMark RushakoffView Answer on Stackoverflow
Solution 2 - PythonEric LeschinskiView Answer on Stackoverflow
Solution 3 - PythonkarantanView Answer on Stackoverflow
Solution 4 - PythonAmberView Answer on Stackoverflow
Solution 5 - PythonVicXView Answer on Stackoverflow