Python3 assert (Assertion)

Document 对象参考手册Python3 Errors and Exceptions

Python assert (assertion) is used to evaluate an expression, and triggers an exception when the expression condition is false.

Assertions can directly return an error when the conditions for program operation are not met, without having to wait for the program to crash after running. For example, if our code can only run on the Linux system, we can first check whether the current system meets the conditions.

The syntax format is as follows:

assert expression

Equivalent to:

if not expression:
    raise AssertionError

assert can also be followed by parameters:

assert expression [, arguments]

Equivalent to:

if not expression:
    raise AssertionError(arguments)

The following are examples of using assert:

>>> assert True     # If the condition is true, execute normally
>>> assert False    # If the condition is false, trigger an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1    # If the condition is true, execute normally
>>> assert 1==2    # If the condition is false, trigger an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>> assert 1==2, '1 is not equal to 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1Not equal to2
>>>

The following example checks whether the current system is Linux. If the condition is not met, it directly triggers an exception without executing the subsequent code:

Example

import sys
assert ('linux' in sys.platform), "This code can only be executed on Linux"

# Code to be executed next

Document 对象参考手册Python3 Errors and Exceptions

Other Extensions