1. 程式人生 > >[python ] 斷言assert的使用

[python ] 斷言assert的使用

python 中的assert 可以簡化程式碼,讓python看起來如此簡單、優雅

一般我們做判斷,並丟擲異常,實現是:


def raise_example(n):
    if not n > 5:
        raise Exception('num is littel than five')

如果使用assert 那麼就更簡單而高效了:


def assert_try(n):
    assert n > 5, 'num is littel than five'

------------------------------------------------
Traceback (most recent call last):
  File "/Users/Desktop/code/assert.py", line 15, in <module>
    assert_try(3)
  File "/Users/Desktop/code/assert.py", line 10, in assert_try
    assert n > 5, 'num is littel than five'
AssertionError: num is littel than five

Process finished with exit code 1

使用場景:

  • 檢查引數型別,類或值
  • 檢查資料結構不變數
  • 檢查“不可能發生”的情況(列表中的重複,相互矛盾的狀態變數。)
  • 在呼叫函式之後,確保其返回是合理的