理解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(斷言)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章