最近每日一更,我這菜雞都有點兒很差意思了python
簡單用法是:shell
assert expression
讓咱們用程序來測試這個expression
,若是expression
至關於False
,那麼raise
一個AssertionError
出來。
即邏輯上等同於:express
if not expression: raise AssertionError
簡單看看這些例子:測試
>>> 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] # 非空列表值得注意一下,雖然說也沒個啥,哈哈 >>> assert not [1, 2] Traceback (most recent call last): File "<ipython-input-48-eae410664122>", line 1, in <module> assert not [1, 2] AssertionError
assert
的異常參數,其實就是在斷言表達式後添加字符串信息,通常用來解釋斷言。格式以下:code
assert expression [, arguments] assert 表達式 [, 參數]
舉例請看以後的代碼ip
老鐵們能夠試着運行一下如下代碼段:element
>>> assert None, 'None若做爲布爾表達式,則至關於False' >>> assert [], '空列表若做爲布爾表達式,則至關於False' >>> assert (), '空元組若做爲布爾表達式,則至關於False' >>> assert {}, '空字典若做爲布爾表達式,則至關於False' >>> assert set(), '空集合若做爲布爾表達式,則至關於False' >>> assert '', '空字符串若做爲布爾表達式,則至關於False'
固然還有奇葩的numpy
字符串
>>> a = np.array([1, 2]) >>> assert a Traceback (most recent call last): File "<ipython-input-45-63e954d94e9b>", line 1, in <module> assert aa ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
是的,你沒看錯,哪裏有numpy
,哪裏就有Use a.any() or a.all()
......input
最後,再試一試這倆吧:it
>>> assert np.array([]) >>> assert np.array([[], []])
是的,只要是空的,甭管是幾維的,都至關於False