How to disable statements in Python?
There are several approaches that affect one process, environment, or one line of code.
I show everyone.
For the whole process
Using the -O flag (capital O) disables all assert statements in the process.
For example:
$ python -Oc "assert False" $ python -c "assert False" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError
Note that by disconnecting, I mean that it also does not execute the expression following it:
$ python -Oc "assert 1/0" $ python -c "assert 1/0" Traceback (most recent call last): File "<string>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero
For the environment
You can also use the environment variable to set this flag.
This will affect every process that uses or inherits the environment.
For example, on Windows, install and then clear the environment variable:
C:\>python -c "assert False" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError C:\>SET PYTHONOPTIMIZE=TRUE C:\>python -c "assert False" C:\>SET PYTHONOPTIMIZE= C:\>python -c "assert False" Traceback (most recent call last): File "<string>", line 1, in <module> AssertionError
Same thing on Unix (using set and unset for related functionality)
One point in code
You continue your question:
if the statement fails, I do not want it to throw an AssertionError error, but continue.
If you want the code to not execute, you can make sure that the control flow does not reach the statement, for example:
if False: assert False, "we know this fails, but we don't get here"
or you may find a confirmation error:
try: assert False, "this code runs, fails, and the exception is caught" except AssertionError as e: print(repr(e))
which prints:
AssertionError('this code runs, fails, and the exception is caught')
and you continue from where you worked with AssertionError .
References
From the assert documentation :
An assertion statement like this:
assert expression
Equivalent
if __debug__: if not expression: raise AssertionError
AND,
the __debug__ built-in variable is True under normal conditions, False when optimization is requested (command line option -O ).
and further
__debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.
From the usage documentation:
-O
Turn on core optimizations. This changes the file name extension for compiled (bytecode) files from .pyc to .pyo. See also PYTHONOPTIMIZE.
and
PYTHONOPTIMIZE
If it is not an empty string, it is equivalent to specify the -O option. If an integer is specified, it is equivalent to specifying -O several times.