• python 高级用法 错误、调试和测试


    Prerequisite

    参考文章:廖雪峰的文章
    常用异常(中文分析):Python 异常处理

    错误处理

    常见写法(以断言语句失败为例)

    # 不追踪错误写法
    # finally 语句写不写都行,但写了一定会执行
    def function():
        try:
            a = 100
            assert a == 10
        except AssertionError as e:
            print("断言语句异常")
        finally:
            print("End")
    
    function()
    """
    断言语句异常
    End
    """
    
    
    # 追踪错误写法
    def function():
        try:
            a = 100
            assert a == 10
        except:
            raise AssertionError("断言语句异常")
        finally:
            print("End")
    
    function()
    """
    End
    Traceback (most recent call last):
      File "C:\Users\WPS\Desktop\Temporary\test.py", line 13, in function
        assert a == 10
    AssertionError
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "C:\Users\WPS\Desktop\Temporary\test.py", line 19, in <module>
        function()
      File "C:\Users\WPS\Desktop\Temporary\test.py", line 15, in function
        raise AssertionError("断言语句异常")
    AssertionError: 断言语句异常
    """
    

    更多规则

    # 捕获多个异常
    try:
        print('try...')
        r = 10 / int('2')
        print('result:', r)
    except ValueError as e:
        print('ValueError:', e)
    except ZeroDivisionError as e:
        print('ZeroDivisionError:', e)
    # 如果没有错误发生
    else:
        print('no error!')
    finally:
        print('finally...')
    print('END')
    

    调试

    方法有 print、assert、logging、pdb、IDE 等,但我只用 logging

    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    s = '0'
    n = int(s)
    logging.debug('n = %d' % n)
    print(10 / n)
    """
    DEBUG:root:n = 0
    Traceback (most recent call last):
      File "c:\Users\WPS\Desktop\Temporary\test.py", line 80, in <module>
        print(10 / n)
    ZeroDivisionError: division by zero
    """
    # 注意除了打印报错信息,n 也打印出来了
    
    
    # 如果开头 logging 的配置换成如下
    logging.basicConfig(level=logging.INFO)
    # 那么就不会打印出 n 了
    

    可替换的地方有开头 level=logging.DEBUG 和报错语句 logging.debug()
    显示报错的等级为:debug < info < warning < error
    选定开头的报错等级,那么报错语句在这个等级以下的,都会显示报错(如果语句报错了)

    单元测试

    基本是测试 python 代码的,使用到了 unittest 模块,内置许多用于测试的函数,如 assertEqual 检验是否相等、assertRaises 检验是否抛出相同异常
    我觉得用不到,就不写了

    文档测试

    讲的是写文档时注释放的是代码执行示例, 如果要执行的化可以用 doctest 模块
    用不到 +2,也不写了

  • 相关阅读:
    [LeetCode] 1072. Flip Columns For Maximum Number of Equal Rows
    [LeetCode] 1730. Shortest Path to Get Food
    [LeetCode] 1005. Maximize Sum Of Array After K Negations
    [LeetCode] 1286. Iterator for Combination
    [LeetCode] 390. Elimination Game
    [LeetCode] 1940. Longest Common Subsequence Between Sorted Arrays
    [LeetCode] 794. Valid TicTacToe State
    [LeetCode] 1162. As Far from Land as Possible
    [LeetCode] 2022. Convert 1D Array Into 2D Array
    [LeetCode] LeetCode 2021勋章
  • 原文地址:https://www.cnblogs.com/CourserLi/p/16525053.html
Copyright © 2020-2023  润新知