This statement causes an AssertionError
when an expression is false. We pass an expression (or value) as the first argument. Python stops and signals the assert call.
With this statement, we can ensure a program's state is correct. And by providing the "O" option on the command line, we can optimize out all assert calls.
Assert()
only has an effect when __debug__ is true. We can disable __debug__ with a command-line parameter.This example program has an assert statement. It causes an AssertionError
unless the two values add up to 110.
value = 10 value2 = 100 # Assert if this expression is not true. assert(value + value2 != 110) print("DONE")C:\pypy3-2.4.0-win32\pypy.exe -O C:\programs\file.pyDONEC:\pypy3-2.4.0-win32\pypy.exe C:\programs\file.pyTraceback (most recent call last): File "C:\programs\file.py", line 8, in <module> assert(value + value2 != 110) AssertionError
When running PyPy or Python, try providing the "-h" option. This will show you help. Then use "-O" to enable optimization (which removes asserts).
-O : skip assert statements
Python is not known for its extreme performance. If your code is critical and cannot bear the burden of assert statements, a faster language might be a good idea.
Assert statements can be used instead of print statements for debugging. With assert()
we can then completely remove all this logic. This helps if we know the program is correct.