How do I disable assertions in Python?
That is, if an assertion fails, I don't want it to throw an AssertionError
, but to keep going.
How do I do that?
How do I disable assertions in Python?
That is, if an assertion fails, I don't want it to throw an AssertionError
, but to keep going.
How do I do that?
Running in optimized mode should do it:
There are multiple approaches that affect a single process, the environment, or a single line of code.
I demonstrate each.
For the whole process
Using the
-O
flag (capital O) disables all assert statements in a process.For example:
Note that by disable I mean it also does not execute the expression that follows it:
For the environment
You can use an environment variable to set this flag as well.
This will affect every process that uses or inherits the environment.
E.g., in Windows, setting and then clearing the environment variable:
Same in Unix (using set and unset for respective functionality)
Single point in code
You continue your question:
If you want the code that fails to be exercised, you can catch either ensure control flow does not reach the assertion, for example:
or you can catch the assertion error:
which prints:
and you'll keep going from the point you handled the
AssertionError
.References
From the
assert
documentation:An assert statement like this:
Is equivalent to
And,
and further
From the usage docs:
and
Call Python with the -O flag:
test.py:
Output:
Use
python -O
:You should NOT disable (most) assertions. They catch unanticipated errors when attention is elsewhere. See Rule 5 in "The power of ten".
Instead, guard some expensive assertion checks by something like:
One way to keep important assertions, and allow
assert
statements to be optimized away is by raising them within a selection statement:Both of the two answers already given are valid (call Python with either
-O
or-OO
on the command line).Here is the difference between them:
-O
Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo.-OO
Discard docstrings in addition to the-O
optimizations.(From the Python documentation)