python assert with and without parenthesis

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

    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.

提交回复
热议问题