[Learning] The dangers of assert in Python (a.k.a know what you're doing!)

There are many ways to find bugs in Python code: the built-in debugger (pdb), a healthy amount of unit tests, a debugger in an IDE like Pycharm or Visual Studio, try/catch statements, if/else statements, assert statements, or the tried and true practice of covering every inch of your codebase in print() statements like it’s going out of style.

Assert statements can help us catch bugs quickly and are far less intrusive than copious amounts of print statements. However, unlike print statements, assert statements can be unexpectedly risky to use!

This article explores how to use asserts safely and what causes them to be unsafe. By the end of this article, you’ll know how to use assert most optimally without inadvertently opening yourself up to security issues.

Using Python assert statements

Using assert is easy! Assert statements are simple statements, which means they can fit in one line of Python code.

Here’s a simple example of an assert statement:

assert expression

In the statement above, you’re asserting that the expression evaluates to True, similar to a boolean check.

Read more here: https://snyk.io/blog/the-dangers-of-assert-in-python/

My notes

A quote from: Python's assert: Debug and Test Your Code Like a Pro

Assertions are a convenient tool for documenting, debugging, and testing code during development. Once you’ve debugged and tested your code with the help of assertions, then you can turn them off to optimize the code for production. Assertions will help you make your code more efficient, robust, and reliable...

In general, you shouldn’t use assertions for data processing or data validation, because you can disable assertions in your production code, which ends up removing all your assertion-based processing and validation code.

But you should know your app and how it's work.

Example in Odoo ERP, the assert statements is used to validate some logic code (a lot's) and (Odoo) can't run with PYTHONOPTIMIZE (-O or -OO) as discussed here:

#odoo #python #learning