What is the assert in Python?

10

@CiganoMorrisonMendez gave me a answer in a previously asked question about Python . And since I'm a beginner in% w / o%, I still do not know what the% w / w% that he indicated in the answer is.

The excerpt from the code he indicated is this:

assert n >= 0

The question remains: How does Python work and when should I use it?

    
asked by anonymous 04.09.2015 / 15:08

2 answers

7

Assert is a run-time check of any condition. If the condition is not true, an AssertionError exception happens and the program stops.

This is not used for "expected" error conditions, such as a network connection that did not open. The objective of the assert is to aid in debugging by verifying the internal sanity of the program.

The Using Assertions Effectively page suggests using to check the parameter types of a function or method. I would not use it for this. The most correct use is to catch those seemingly impossible conditions of error (but they end up happening anyway).

If the algorithm itself causes an error in case of inconsistency, I do not see why to use assert. In the following code, it is critical that foo () return a number between 0 and 5, but the code itself ensures that an out-of-range number throws an exception:

n = foo()
s = ["a", "b", "c", "d", "e", "f"][n]

On the other hand, if "n" is critical but it is used for a math operation, which would not fail if n is out of range, then the assert is interesting:

n = foo()
assert n >= 0 and n <= 5
s = chr(ord('a') + n)
    
04.09.2015 / 15:19
4
The assert exists in most programming languages and always has the same function, guarantee a condition to continue executing the code

.

If the condition is not met, an exception is thrown, and execution is aborted.

The example you cited:

assert n >= 0

It will throw an exception if n is not greater than 0.

View this post in the SO-en .

04.09.2015 / 15:15