jemnotesversion 2 / featuring this entry or see all/search

Mar 17
The brief version first:
# fine.
assert expr1, expr2

# WRONG!
assert(expr1, expr2)
Be very careful with the syntax of assertions in Python! If you get the syntax wrong, the assertions will just always hold. This is particularly disastrous, as assertions are usually used to expose hidden bugs.
The exact syntax that you should use is assert expr1, expr2. This tests expr1 in the boolean sense, and raises an exception with value str(expr2) if expr1 is False. You can also just use assert expr1, which won’t give a special message. Note the total lack of brackets. If you insert parentheses, though, as in assert(thing1, thing2), what you are really doing is calling assert (thing1, thing2). That is, an assertion with expr1 being (thing1, thing2)! This will never evaluate to False, so you will never get an error.