CodeQL documentation

An assert statement has a side-effect

ID: py/side-effect-in-assert
Kind: problem
Severity: error
Precision: high
   - reliability
   - maintainability
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

All code defined in assert statements is ignored when optimization is requested, that is, the program is run with the -O flag. If an assert statement has any side-effects then the behavior of the program changes when optimization is requested.


Move all expressions with side-effects out of assert statements.


In the example, the exit code from is checked against 0, but the entire expression is called from within an assert statement. If the code is ever run, then the not only the assertion itself, but also the external call, will be discarded. It is better to save the result of to a temporary variable, and to assert that variable to be 0.

assert['run-backup']) == 0