Instance Usage of python assert Assertion

  • 2021-12-04 10:39:13
  • OfStack

Assertion declaration is a convenient way to debug programs.

1. Assertion can be considered an debug tool, and the implementation of Python conforms to this design concept. The execution of the assert statement depends on __debug__, and the default value is True.

2. If __debug__ is True, only the assert statement is executed.

Instances

assert can declare two expression at the same time, for example, assert expression1, expression2 equivalent to


if __debug__:
if not expression1: raise AssertionError(expression2)

If the script file is executed with the -O parameter, __debug__ is False.

Extension of knowledge points:

The simple usage is:

assert expression

Let's test this expression with a program. If expression is equivalent to False, then raise1 AssertionError will come out.

That is, logically equivalent to:


if not expression:
 raise AssertionError

Take a brief look at these examples:


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

>>> assert 1==1
>>> assert 1==0
Traceback (most recent call last):
 File "<pyshell#1>", line 1, in <module>
 assert 1==0
AssertionError

>>> assert [1, 2] #  Non-empty lists are worth noting 1 Next, although it's nothing, haha 
>>> assert not [1, 2]
Traceback (most recent call last):
 File "<ipython-input-48-eae410664122>", line 1, in <module>
 assert not [1, 2]
AssertionError

Related articles: