What is assert
assert syntax:
assert_stmt ::= "assert" expression ["," expression]
Example:
assert 1 == 2, 'assertion is wrong' Traceback (most recent call last): File "assert.py", line 4, in <module> assert 1 == 2, 'assertion is wrong' AssertionError: assertion is wrong
Equivalent to
if __debug__: if not expression1: raise AssertionError(expression2)
assert(1 == 2, 'This should fail') # 输出 <ipython-input-8-2c057bd7fe24>:1: SyntaxWarning: assertion is always true, perhaps remove parentheses? assert(1 == 2, 'This should fail')
assert usage
def apply_discount(price, discount): updated_price = price * (1 - discount) assert 0 <= updated_price <= price, 'price should be greater or equal to 0 and less or equal to original price' return updated_price
If you assert conditions for False, will raise
apply_discount(100, 0.2) 80.0 apply_discount(100, 2) AssertionError: price should be greater or equal to 0 and less or equal to original price
2. Background want to know the average selling price of each item, the algorithm is the total sales / Number of sales:
def calculate_average_price(total_sales, num_sales): assert num_sales > 0, 'number of sales should be greater than 0' return total_sales / num_sales
Joined assert statement, the number of sales provisions must be greater than zero.
3. Check whether the input list
DEF FUNC (INPUT): Assert the isinstance (INPUT, List), ' INPUT MUST BE type of List ' # The following operations are based on the premise: input must List IF len (INPUT). 1 == : ... elif len ( the INPUT) == 2 : ... the else : ...
assert error example
assert checks can be turned off, such as when running a Python program, adding -O This option will let assert failure. Therefore, once assert checking is turned off, user_is_admin () and course_exist () These two functions will not be executed. This can lead to serious problems:
def delete_course(user, course_id): assert user_is_admin(user), 'user must be admin' assert course_exist(course_id), 'course id must exist' delete(course_id)
For programs in some of the run-time error, or starting exception handling
def delete_course(user, course_id): if not user_is_admin(user): raise Exception('user must be admin') if not course_exist(course_id): raise Exception('coursde id must exist') delete(course_id)
reference
Geek Time "Python core technology and practical" column