# 使用 assert

May 4, 2022

## assert 陳述

``````assert <test>, <message>
``````

`test` 是狀態測試，而 `message` 是斷言失敗時所要呈現訊息。例如，在定義的 `Account` 類別裡，存款的時候不能提負數，提款的時候也不能是負數，呼叫 `deposit``withdraw` 時傳入的值必然是大於 0，這時可以使用斷言檢查：

``````class Account:
def __init__(self, number, name):
self.number = number
self.name = name
self.balance = 0

def deposit(self, amount):
assert amount > 0, '必須是大於 0 的正數'
self.balance += amount

def withdraw(self, amount):
assert amount > 0, '必須是大於 0 的正數'
if amount <= self.balance:
self.balance -= amount
else:
raise RuntimeError('balance not enough')

a = Account('E122', 'Justin')
a.deposit(-1)    # AssertionError: 必須是大於 0 的正數
``````

``````if x > 0:
# do some
...
else:
assert x == 0, 'x 此時一定要是 0，不會是負數'
# do other
...
``````

``````class Stack:
def __init__(self):
self.idx = 0
self.data = []

def push(self, c):
length = len(self.data)
self.data.append(c)
assert (length + 1) == len(self.data)

def pop(self):
length = len(self.data)
ele = self.data.pop()
assert (length - 1) == len(self.data)
return ele
``````

## 停用斷言

``````print(__debug__)
assert False
``````

``````assert test, 'some message' # test 結果為 True 或 False
``````

``````if __debug__:
if not test:
raise AssertionError('some message')
``````