Personal blog of Matthias M. Fischer


Assert Statements are Removed in Optimised Python Code

16th October 2022

Introduction

This article is basically just a short note on something a good friend of mine told me yesterday and which surprised me a lot. Thus, I wanted to write it down here, because I think it is worth sharing. The title of this post already tells you everything you need to know: One may compile a piece of Python code applying some optimisations by using the -O flag; however this will leave out all the assert statements in it. Using assert in (potentially optimised) production code e.g. for checking whether parameters passed to a function fulfill certain requirements thus might be a bad idea.

A Demonstration

Consider the following simple statement:

assert False

If we start a normal Python session by running python in our favourite terminal, and disassemble the previous statement using the dis() function from the dis module, we get the following result:

dis.dis("assert False")
  1           0 LOAD_ASSERTION_ERROR
              2 RAISE_VARARGS            1

As expected, an assertion error is loaded and raised.

However, if we run a Python session with the -O flag by using python -O, then we get:

dis.dis("assert False")
  1           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE

In other words, no error is raised and the code terminates successfully returning 0.

Thus, if we were to define some function that uses assert statements to guarantee that its parameters only contain valid values, this strategy would fail as soon as we want to compile our code in an optimised way.

Conclusions

Do not use assert in (potentially optimised) production code :-).