Python - assert (assertion)

About

Before a program is not perfect, we do not know where the program will go wrong, rather than let it run most crashes, it is better to crash when an error condition occurs.

At this time, we should use the assertion assert, assertion format usage in Python is simple.

Assert assert refers to the expected conditions specified by the user, which is triggered when a user-defined constraint condition is not satisfied AssertionErrorabnormal, therefore assert statement can be seen as conditional expressions raise statement. Its main function is to help programmers to debug procedures to ensure the accuracy of the program is running, usually in the development and debugging phase of use.

Use assert the

Assert the general usage

assert condition

assert judgment condition (condition) is satisfied, if not true, an exception is thrown, the logically equivalent to:

if not condition:
    raise AssertionEerror()
    
a = ''
# assert a

if not a:
    raise AssertionError('a等于空')

Another form of assert

assert condition, expression

If the condition is False, a description will raise the error AssertionError out expression, logically equivalent to:

if not condition:
    raise AssertionEerror(expression)

a = ''
# assert a, 'a是空的啦'

if not a:
    raise AssertionError('a等于空')

Enable, disable assertions

First, you must know that there are two modes Python interpreter at run time:

  • Debug mode, in this mode, the built-in read-only variable __debug__to True.
  • Optimization mode, when using the option -Oto run, that python.exe -O demo.pyis optimized mode, the built-in read-only variable __debug__to False.
    Examples of view, there is a Python file content:
a = ''
# assert a, 'a是空的啦'

if not a:
    raise AssertionError('a等于空')

We are two modes to run the file, first look at the normal debug mode:

M:\>python testsss.py
Traceback (most recent call last):
  File "testsss.py", line 56, in <module>
    assert a, 'a是空的啦'
AssertionError: a是空的啦

At this point the above Python file in debug mode, triggered assert conditional execution, and throw AssertionErroran exception.
Let's look at optimization mode:

M:\>python -O testsss.py
Traceback (most recent call last):
  File "testsss.py", line 59, in <module>
    raise AssertionError('a等于空')
AssertionError: a等于空

Content can be discovered by an error in tuning mode, the assertion is disabled, we are being given a handwritten statement to determine if triggered.

some advices

In the tuning mode, to a certain extent, improve the efficiency of program execution, but this is equivalent planted a mine.
So what should we do when to use assertions? In general, if there is no particular purpose, it should be used to assert:

  • Defensive programming environment.
  • Checking that the program logic is running.
  • Check contract, such as pre / post condition check.
  • Program constants.
  • Check the documentation.
  • Code test.

Of course, in some cases, we do not recommend the use of assertions:

  • Do not use the test data provided by the user, or those who need to change where it is needed to check in all cases
  • Do you think might fail to check in normal use areas. Assertion failed for very special conditions. Your users will not see a AssertionError, if you see, that is a must repair the defect.
  • Do not just particular assertion than a definitive test plus a little and use it to trigger an exception. Assertion code writers are not lazy shortcut.
  • Do not assert a public library to check the input parameters, the caller because you can not control and can not guarantee that it does not destroy the function of the contract.
  • Do not assert any errors you expect to modify. In other words, you do not have any reason to capture in a product code AssertionErrorexception.
  • Do not use too much assertion that the code becomes obscure.

The last extension

By default, __debug__a constant, including None, False, True these constants can not be reassigned (even if the property names assigned to them, will lead to a SyntaxError), and therefore they can be regarded as "True" constants.

if __debug__:
    print('debug模式')

About -O, in the command line environment, the use of python.exe -O demo.pytime, will be deleted (can be understood as ignored) assert any statements and based on __debug__code values. See PEP 488.
About -OO, in the command line environment, the use of python.exe -OO demo.pytime, would discard the document string. See PEP 488.

def foo():
    """ docstrings """
    pass

if __debug__:
    help(foo)

The code above, use python.exe demo.pywill return the document information foo function. And use python.exe -OO demo.py, the document information foo function will not return.



Welcome treatise, that's All
See Also: Python in when to use assert assert | A Python 3 assert (assertion) | assert assertion treatment [Python] | Python assertion assert in understanding and usage | https://docs.python.org/3/ Reference / simple_stmts.html at The #-the Assert-of Statement | https://docs.python.org/3/library/constants.html#__debug__ | https://docs.python.org/3/using/cmdline.html# O-cmdoption | https://www.python.org/dev/peps/pep-0488

About

Before a program is not perfect, we do not know where the program will go wrong, rather than let it run most crashes, it is better to crash when an error condition occurs.

At this time, we should use the assertion assert, assertion format usage in Python is simple.

Assert assert refers to the expected conditions specified by the user, which is triggered when a user-defined constraint condition is not satisfied AssertionErrorabnormal, therefore assert statement can be seen as conditional expressions raise statement. Its main function is to help programmers to debug procedures to ensure the accuracy of the program is running, usually in the development and debugging phase of use.

Use assert the

Assert the general usage

assert condition

assert judgment condition (condition) is satisfied, if not true, an exception is thrown, the logically equivalent to:

if not condition:
    raise AssertionEerror()
    
a = ''
# assert a

if not a:
    raise AssertionError('a等于空')

Another form of assert

assert condition, expression

If the condition is False, a description will raise the error AssertionError out expression, logically equivalent to:

if not condition:
    raise AssertionEerror(expression)

a = ''
# assert a, 'a是空的啦'

if not a:
    raise AssertionError('a等于空')

Enable, disable assertions

First, you must know that there are two modes Python interpreter at run time:

  • Debug mode, in this mode, the built-in read-only variable __debug__to True.
  • Optimization mode, when using the option -Oto run, that python.exe -O demo.pyis optimized mode, the built-in read-only variable __debug__to False.
    Examples of view, there is a Python file content:
a = ''
# assert a, 'a是空的啦'

if not a:
    raise AssertionError('a等于空')

We are two modes to run the file, first look at the normal debug mode:

M:\>python testsss.py
Traceback (most recent call last):
  File "testsss.py", line 56, in <module>
    assert a, 'a是空的啦'
AssertionError: a是空的啦

At this point the above Python file in debug mode, triggered assert conditional execution, and throw AssertionErroran exception.
Let's look at optimization mode:

M:\>python -O testsss.py
Traceback (most recent call last):
  File "testsss.py", line 59, in <module>
    raise AssertionError('a等于空')
AssertionError: a等于空

Content can be discovered by an error in tuning mode, the assertion is disabled, we are being given a handwritten statement to determine if triggered.

some advices

In the tuning mode, to a certain extent, improve the efficiency of program execution, but this is equivalent planted a mine.
So what should we do when to use assertions? In general, if there is no particular purpose, it should be used to assert:

  • Defensive programming environment.
  • Checking that the program logic is running.
  • Check contract, such as pre / post condition check.
  • Program constants.
  • Check the documentation.
  • Code test.

Of course, in some cases, we do not recommend the use of assertions:

  • Do not use the test data provided by the user, or those who need to change where it is needed to check in all cases
  • Do you think might fail to check in normal use areas. Assertion failed for very special conditions. Your users will not see a AssertionError, if you see, that is a must repair the defect.
  • Do not just particular assertion than a definitive test plus a little and use it to trigger an exception. Assertion code writers are not lazy shortcut.
  • Do not assert a public library to check the input parameters, the caller because you can not control and can not guarantee that it does not destroy the function of the contract.
  • Do not assert any errors you expect to modify. In other words, you do not have any reason to capture in a product code AssertionErrorexception.
  • Do not use too much assertion that the code becomes obscure.

The last extension

By default, __debug__a constant, including None, False, True these constants can not be reassigned (even if the property names assigned to them, will lead to a SyntaxError), and therefore they can be regarded as "True" constants.

if __debug__:
    print('debug模式')

About -O, in the command line environment, the use of python.exe -O demo.pytime, will be deleted (can be understood as ignored) assert any statements and based on __debug__code values. See PEP 488.
About -OO, in the command line environment, the use of python.exe -OO demo.pytime, would discard the document string. See PEP 488.

def foo():
    """ docstrings """
    pass

if __debug__:
    help(foo)

The code above, use python.exe demo.pywill return the document information foo function. And use python.exe -OO demo.py, the document information foo function will not return.



Welcome treatise, that's All
See Also: Python in when to use assert assert | A Python 3 assert (assertion) | assert assertion treatment [Python] | Python assertion assert in understanding and usage | https://docs.python.org/3/ Reference / simple_stmts.html at The #-the Assert-of Statement | https://docs.python.org/3/library/constants.html#__debug__ | https://docs.python.org/3/using/cmdline.html# O-cmdoption | https://www.python.org/dev/peps/pep-0488

Guess you like

Origin www.cnblogs.com/qq834761298/p/12164725.html