Assertion
一句话解释
assertion (assert) 检查 条件 at 运行时 and raises AssertionError 如果 它 是 假, used for 调试.
用大白话说
assertion 是调试 aid 那个检查条件是 真. 如果条件是 假, AssertionError 是 raised (使用可选消息). 语法是 assert condition, message.
Assertions are for catching programming errors (bugs), not for handling expected runtime errors. Use them to verify invariants, preconditions, and postconditions during development.
Important: assertions can be disabled with python -O (optimized mode), which strips all assert statements. Never use assertions for validation that must run in production — use explicit if/raise instead. Assertions are for development and testing.
示例
def calculate_average(numbers):
assert len(numbers) > 0, "Cannot average an empty list"
return sum(numbers) / len(numbers)
print(calculate_average([1, 2, 3])) # 2.0
# This raises AssertionError
# calculate_average([])
# Assertions can be disabled with: python -O script.pyassert 检查 条件 and raises AssertionError 如果 假. Used for 调试, 不 production validation.
常见混淆
容易混淆的对象: 异常
关键区别: assertion 检查 for programming bugs and 能 是 禁用 in optimized 模式. 异常 (raise) handles expected 运行时 条件 and 总是 运行. Use assertions for 调试; use 异常 for production 错误 handling.
相关术语
相关资源
相关课程
- 单元 测试
Assertions in 测试.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。