Python3 assert(斷言)
Python assert(斷言)用於判斷一個運算式,在運算式條件為 false 的時候觸發異常。
斷言可以在條件不滿足程式運行的情況下直接返回錯誤,而不必等待程式運行後出現崩潰的情況,例如我們的代碼只能在 Linux 系統下運行,可以先判斷當前系統是否符合條件。
語法格式如下:
assert expression
等價於:
if not expression: raise AssertionError
assert 後面也可以緊跟參數:
assert expression [, arguments]
等價於:
if not expression: raise AssertionError(arguments)
以下為 assert 使用實例:
>>> assert True # 條件為 true 正常執行
>>> assert False # 條件為 false 觸發異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # 條件為 true 正常執行
>>> assert 1==2 # 條件為 false 觸發異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==2, '1 不等於 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 不等於 2
>>>
>>> assert False # 條件為 false 觸發異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # 條件為 true 正常執行
>>> assert 1==2 # 條件為 false 觸發異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==2, '1 不等於 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 不等於 2
>>>
以下實例判斷當前系統是否為 Linux,如果不滿足條件則直接觸發異常,不必執行接下來的代碼:
實例
import sys
assert ('linux' in sys.platform), "該代碼只能在 Linux 下執行"
# 接下來要執行的代碼
assert ('linux' in sys.platform), "該代碼只能在 Linux 下執行"
# 接下來要執行的代碼