Assertions are a feature specifically designed to allow to easily disable the checks in the production code. You can do so by compiling your Python code to a .pyc
file with -O
or -OO
flags. You can also run Python code with the PYTHONOPTIMIZE
environment variable set to non-zero value to get that optimization.
For the most part, it doesn't really matter, you should only really care if you have a tight loop with thousands of asserts per second or more. Other than that, some assertion comparisons, like collections, could be so expensive, that even making one could have a significant cost. If something like this happens in your code, you might want to get rid of it in the way mentioned or otherwise (for open-source reasons you might want to just remove it with e.g. regex).
Those assertions that aren't computationally expensive, could remain useful in production, because bugs happen in production as well - but in such case convert them to normal if
checks and raise
exceptions.
PYTHONOPTIMIZE Environment Variable Example
Set the environment variable PYTHONOPTIMIZE
to a non-zero value, then run Blender:
C:\Users\w10>e:
E:\>cd E:\Program Files\Blenders\stable\blender-3.6.2+stable.e53e55951e7a
E:\Program Files\Blenders\stable\blender-3.6.2+stable.e53e55951e7a>set PYTHONOPTIMIZE=1
E:\Program Files\Blenders\stable\blender-3.6.2+stable.e53e55951e7a>echo %PYTHONOPTIMIZE%
1
E:\Program Files\Blenders\stable\blender-3.6.2+stable.e53e55951e7a>blender
Read prefs: "C:\Users\w10\AppData\Roaming\Blender Foundation\Blender\3.6\config\userpref.blend"
Then go to the Scripting tab and confirm in the Python console that the environment variable is set:
>>> import os
>>> os.getenv('PYTHONOPTIMIZE')
'1'
Now in the text block area, from menu Templates choose Python → Addon Add Object, and modify the add_object
function to simply:
def add_object(self, context):
print("normal print")
assert 1 == 2, "this assert should always report an error"
now run the script, and use the new operator:
You won't see the assertion error, only normal print
in the system console.