Search code examples
pythonassertassertion

Python assert with paranthesis allows for only part of the condition to be written within them


Could someone please explain me why this absolutely weird syntax works in Python (I tested in Python 3.7)? Functionally, it seems perfectly equivalent to the logically corect assert(5+1 == 6), but I have no idea why this would be valid syntax.

assert(5) + 1 == 6

Solution

  • assert is not a function; it's a statement.

    In both cases, your parentheses are part of the expression following the keyword assert. The expressions (5) + 1 == 6, (5+1 == 6), and 5 + 1 == 6 are equivalent, with the parentheses in the first two cases being unnecessary.

    You can see the parser treats them identically:

    >>> import ast
    >>> ast.dump(ast.parse("assert(5) + 1 == 6"))
    'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
    >>> ast.dump(ast.parse("assert(5 + 1 == 6)"))
    'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
    >>> ast.dump(ast.parse("assert 5 + 1 == 6"))
    'Module(body=[Assert(test=Compare(left=BinOp(left=Num(n=5), op=Add(), right=Num(n=1)), ops=[Eq()], comparators=[Num(n=6)]), msg=None)])'
    

    or letting Python compare the strings for you,

    >>> exprs = ["assert(5) + 1 == 6", "assert(5 + 1 ==  6)", "assert 5 + 1 == 6"]
    >>> len(set(ast.dump(ast.parse(x)) for x in exprs))
    1
    

    More formally, the assert statement consists of the assert keyword followed by one or two additional expressions.

    assert_stmt: 'assert' test [',' test]
    

    The first one is evaluated as a Boolean expression, producing True or False as the result. The value of the second one, if present, is used to construct the AssertionError raised by the statement if the first expression is False.

    >>> assert False
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError
    >>> assert False, 3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError: 3
    >>> assert True
    >>> assert True, 3