The assert is an execution-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 has not opened. The purpose of assert is to assist in debugging by checking the internal health of the program.
The page Using Assertions Effectively suggests to use to check the types of parameters of a function or method. I would not use for this. The most correct use is to pick up those seemingly impossible error conditions (but end up happening anyway).
If the algorithm itself causes an error in case of inconsistency, I don’t see why to use the assert. In the following code, it is critical that foo() returns a number between 0 and 5, but the code itself ensures that an out-of-range number raises 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 mathematical operation, which would not fail if n is outside the range, then the assert is interesting:
n = foo()
assert n >= 0 and n <= 5
s = chr(ord('a') + n)
You did some research on this?
– ramaral
I found some things in English. From what I understand, it seems to throw an exception if the condition is false. That’s what I think, I’m not sure
– Wallace Maxters
https://pythonhelp.wordpress.com/2012/09/09/programe-defensivamente-com-assercoes/
– Dalton Menezes
@Daltonmenezes, wouldn’t it be important to add a few things to the answer? I realized there’s a way to get a message across when the
AssertionError
is called.– Wallace Maxters
My "last name" is with z at the end. Mendez.
– Leonel Sanches da Silva
By complementing the responses, you can pass a message to Exception using
assert condicao, mensagem
(ex: `assert n == 1, "The value of n is different from 1")– Paulo Marques