Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of "assert" in Python?

I have been reading some source code and in several places I have seen the usage of assert.

What does it mean exactly? What is its usage?

like image 885
Hossein Avatar asked Feb 28 '11 13:02

Hossein


People also ask

What is the use of assert function?

The assert() function tests the condition parameter. If it is false, it prints a message to standard error, using the string parameter to describe the failed condition. It then sets the variable _assert_exit to one and executes the exit statement.

What are assert statements in Python?

What Are Assertions? In Python, assertions are statements that you can use to set sanity checks during the development process. Assertions allow you to test the correctness of your code by checking if some specific conditions remain true, which can come in handy while you're debugging code.

When should I use assert?

You can use an assert to check if your logical assumption is correct. You can also use assert statements to check if the control flow is correct or not. For example, if you have a function that returns a value, you may want to put an assert statement. However, you may get a 'non-reachable' code error.

Why do we use assert in testing?

Assertions are used for validating a test case and helps us understand if a test case has passed or failed. The assertion is considered to be met if the actual result of an application matches with that of the expected result.


2 Answers

The assert statement exists in almost every programming language. It has two main uses:

  1. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails. A type error in Python, for example, can go through several layers of code before actually raising an Exception if not caught early on.

  2. It works as documentation for other developers reading the code, who see the assert and can confidently say that its condition holds from now on.

When you do...

assert condition 

... you're telling the program to test that condition, and immediately trigger an error if the condition is false.

In Python, it's roughly equivalent to this:

if not condition:     raise AssertionError() 

Try it in the Python shell:

>>> assert True # nothing happens >>> assert False Traceback (most recent call last):   File "<stdin>", line 1, in <module> AssertionError 

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

assert False, "Oh no! This assertion failed!" 

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py 

See here for the relevant documentation.

like image 130
slezica Avatar answered Sep 28 '22 00:09

slezica


Watch out for the parentheses. As has been pointed out in other answers, in Python 3, assert is still a statement, so by analogy with print(..), one may extrapolate the same to assert(..) or raise(..) but you shouldn't.

This is wrong:

assert(2 + 2 == 5, "Houston we've got a problem") 

This is correct:

assert 2 + 2 == 5, "Houston we've got a problem" 

The reason the first one will not work is that bool( (False, "Houston we've got a problem") ) evaluates to True.

In the statement assert(False), these are just redundant parentheses around False, which evaluate to their contents. But with assert(False,) the parentheses are now a tuple, and a non-empty tuple evaluates to True in a boolean context.

like image 24
Evgeni Sergeev Avatar answered Sep 28 '22 01:09

Evgeni Sergeev