• python assert函数解析(最清晰的解释)


    欢迎关注WX公众号:【程序员管小亮】

    python assert的作用:

    assert函数用于程序调试

    Python 官方文档解释https://docs.python.org/3/reference/simple_stmts.html#assert

    “Assert statements are a convenient way to insert debugging assertions into a program”

    assert断言语句是将调试断言插入程序的一种方便方法。

    使用assert断言语句是一个非常好的习惯,python assert断言句语格式及用法很简单。在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行到最后崩溃,不如在出现错误条件时就崩溃,这样在跑大规模程序的时候不会过多的浪费时间和计算资源,这时候就需要assert断言的帮助。

    1、The simple form:
    assert expression
    

    该形式用来测试断言的expression语句,如果expression是True,那么什么反应都没有。但是如果expression是False,那么会报错AssertionError

    例子

    assert 1==0
    
    ---------------------------------------------------------------------------
    AssertionError                            Traceback (most recent call last)
    <ipython-input-4-b09d6b060198> in <module>()
    ----> 1 assert 1==0,
    
    AssertionError:
    

    不出错时,什么反应都没有:

    assert 1==1
    
    2、The extended form:
    assert expression1, expression2
    

    assert断言语句可以添加异常参数,也就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:

    assert expression [, arguments]
    assert 表达式 [, 参数]
    

    例子

    assert 1==0, "出错了"
    
    ---------------------------------------------------------------------------
    AssertionError                            Traceback (most recent call last)
    <ipython-input-4-b09d6b060198> in <module>()
    ----> 1 assert 1==0, "出错了"
    
    AssertionError: 出错了
    

    不出错时,依旧什么反应都没有:

    assert 1==1, "出错了"
    
    3、The Equivalent expression:

    The simple form, 断言assert expression, 等价于:

    if __debug__:
        if not expression: raise AssertionError
    

    官方文档中给出了下面一段话作为理解:

    These equivalences assume that debug and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable debug is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

    Assignments to debug are illegal. The value for the built-in variable is determined when the interpreter starts.

    这种“等价”假设了__debug__和AssertionError引用了具有这些名称的内置变量。在当前实现中,内置变量__debug__在正常情况下为True,在请求优化时为False(命令行选项-O)。当编译时请求优化时(内置变量__debug__为False),当前代码生成器不会为assert语句发出代码。注意,没有必要在错误消息中包含失败表达式的源代码;它将作为堆栈跟踪的一部分显示。

    赋值给_debug__是非法的。内置变量的值在解释器启动时就是确定的。

    (以上是个人的蹩脚翻译,欢迎指正)

    python课程推荐。
    在这里插入图片描述

  • 相关阅读:
    图匹配板子
    线性基
    Berlekamp-Massey algorithm
    组合/概率/形式幂级数/多项式/集合幂级数的题
    费用流 Dijkstra 原始对偶方法(primal-dual method)
    UVA-12304
    二项式系数
    卡特兰数
    多项式模板
    工具
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13302850.html
Copyright © 2020-2023  润新知