python assert with and without parenthesis

后端 未结 5 922
南笙
南笙 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:26

    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

提交回复
热议问题