assert condition
if not condition:
raise AssertionError()
>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
assert False, "Oh no! This assertion failed!"
python -O script.py
assert(2 + 2 == 5, "Houston we've got a problem")
assert 2 + 2 == 5, "Houston we've got a problem"
if __debug__:
if not expression: raise AssertionError
>>> assert 5 > 2
>>> assert 2 > 5
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.AssertionError:
Python 中断言的目的是通知开发人员程序中不可恢复的错误。
断言并非旨在表示预期的错误情况,例如 “找不到文件”,用户可以在其中采取纠正措施(或仅重试)。
另一种看待它的方式是说断言是代码中的内部自检 。它们通过在代码中声明某些条件是不可能的来工作的。如果不满足这些条件,则意味着程序中存在错误。
如果您的程序没有错误,则这些情况将永远不会发生。但是,如果确实发生了其中一种情况,则该程序将因声明错误而崩溃,并确切地告诉您触发了哪个 “不可能” 条件。这使查找和修复程序中的错误变得更加容易。
这是我写的有关 Python 断言的教程的摘要:
Python 的 assert 语句是一种调试辅助工具,而不是用于处理运行时错误的机制。使用断言的目的是让开发人员更快地找到错误的可能根本原因。除非程序中存在错误,否则永远不会引发断言错误。
if __debug__:
if not <expression>: raise AssertionError
if __debug__:
if not <expression1>: raise AssertionError, <expression2>
>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>>
Assert statements are a convenient way to insert debugging assertions into a program
def chkassert(num):
assert type(num) == int
chkassert('a')
Traceback (most recent call last):
File "b.py", line 5, in <module>
chkassert('a')
File "b.py", line 2, in chkassert
assert type(num) == int
AssertionError
assert 1>0 #normal execution
assert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#AssertionError