Python规范:用用assert

什么是assert

  assert的语法:

assert_stmt ::=  "assert" expression ["," expression]

  例:

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

  相当于

if __debug__:
    if not expression1: raise AssertionError(expression2)
  assert 在程序中的作用,是对代码做一些 internal 的 self-check。使用 assert,就表示你很确定。这个条件一定会发生或者一定不会发生。
  注意:不能在使用assert时加上括号
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 的用法

  举例几个常用的场景。
  1.商品打折。要求输入为原来的价格和折扣,输出是折后的价格   
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

  如果assert的条件为False,会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.后台想知道每个商品的平均销售价格,算法是销售总额 / 销售数目:

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

  加入了 assert 语句,规定销售数目必须大于 0.

  3.检查输入是否list

def func(input):
    assert isinstance(input, list), 'input must be type of list'
    # 下面的操作都是基于前提:input 必须是 list
    if len(input) == 1:
        ...
    elif len(input) == 2:
        ...
    else:
        ... 

assert 错误示例

   assert 的检查是可以被关闭的,比如在运行 Python 程序时,加入-O这个选项就会让 assert 失效。因此,一旦 assert 的检查被关闭,user_is_admin() 和 course_exist() 这两个函数便不会被执行。这就会导致严重问题:

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)

  对于程序中的一些 run-time error,还是得用异常处理

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)  

参考

   极客时间《Python核心技术与实战》专栏

 
 
 
 
 
 
 
 
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/xiaoguanqiu/p/11301253.html