144

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.

3
  • Thanks for the helpful answers. The distinction between keywords and built-in functions seems subtle. Here is a list of keywords, for which I presume, parens should be left out: docs.python.org/reference/lexical_analysis.html#keywords
    – new name
    Jun 24, 2010 at 17:31
  • 2
    One difference is that you can redefine built-in functions but can't do so with keywords (not that the former is a good idea).
    – new name
    Jun 24, 2010 at 17:34
  • It's not function vs keyword distinction, but function call vs statement. (for example - print used to be a statement, and worked without parentheses). Apr 18, 2018 at 8:51

6 Answers 6

160

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

4
  • 12
    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 Jun 24, 2010 at 17:05
  • It's worth further emphasizing that statements of the form assert(test, message) probably wrong, and certainly confusing. No parens!
    – tcarobruce
    Jun 24, 2010 at 17:24
  • 34
    So, what is the proper way to indent a long assert statement, w.r.t. PEP8? Seems impossible.
    – stantonk
    Apr 11, 2013 at 16:53
  • 9
52

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.

1
  • 7
    Is there doc on what we should use instead of assert? Assert seems like such a logical name for validating, and it has the behavior desired, eg show a special message upon error. May 21, 2019 at 20:22
30

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'
)
1
  • 2
    Interesting idea. I hate backslashes for continuation, and this is an alternative to wrapping assert in a utility function (which was my solution). Apr 18, 2018 at 8:53
20

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.

0
1

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

0

assert statement with or without parentheses as shown below are the same:

assert (x == 3)
assert x == 3

And, other statements such as if, while, for and del with or without parentheses as shown below are also the same:


if (x == "Hello"):
if x == "Hello":

while (x == 3):
while x == 3:

for (x) in (fruits):
for x in fruits:


del (x)
del x

In addition, basically, most example python code which I've seen so far doesn't use parentheses for assert, if, while, for and del statements so I prefer not using parentheses for them.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.