python assert with and without parenthesis

后端 未结 5 986
南笙
南笙 2021-01-30 02:42

Here are four simple invocations of assert:

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

&g         


        
5条回答
  •  情话喂你
    2021-01-30 03:30

    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.

提交回复
热议问题