Python中assert的使用


1. 定义:Assert statements are a convenient way to insert debugging assertions into a program

 

2.依赖于__debug__变量,默认值为True 当不满足条件返回False

 

3.使用场景:检查先验条件时使用断言,检查后验条件时使用异常

例如 读取文件场景,判断文件格式使用断言,判断文件是否存在使用异常,因为存在后续逻辑处理。

  def read_file(path):

    #判断是否为str类型,先验条件

    assert isinstance(path,str) 

    #判断是否存在 后验条件 逻辑判断

    if not os.path.exists(path):

      raise FileNotFoundError()

例如 检查参数是否合理场景 当我们已知参数是可列举的指定列表时,使用断言防止参数传递错误

  assert spider in ["bigfile", "dynamic"]
       assert proxy_type in [None, "normal", "cross"]


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM