理解assert语句in Python

  • Assert Statements

    Python’s assert statement is a debugging aid that tests a condition.

    If the condition is true, it does nothing and your program just continues to execute. But if the assert condition evaluates to false, it raises an AssertionError exception with an optional error message.

    The proper use of assertions is to inform developers about unrecoverable errors in a program.

    Another way to look at it is to say that assertions are internal self-checks for your program. They work by declaring some conditions as impossible in your code. If one of these conditions doesn’t hold that means there’s a bug in the program.

    To summarize, Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there’s a bug in your program.

  • Python’s Assert Syntax

    It’s always a good idea to study up on how a language feature is actually implemented in Python before you start using it.

    assert_stmt ::= "assert" expression1 ["," expression2]

    In this case expression1 is the condition we test, and the optional expression2 is an error message that’s displayed if the assertion fails.

    At execution time, the Python interpreter transforms each assert statement into roughly the following:

    if __debug__:
        if not expression1:
            raise AssertionError(expression2)
    

    You can use expression2 to pass an optional error message that will be displayed with the AssertionError in the traceback.

  • References

  1. Assert Statements in Python
  2. tutorialspoint : Assertions in Python
  3. 菜鸟教程 : Python3 assert(断言)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值