A must-read article for those who use assert operation for data validation.
Photo by Christopher Gower on Unsplash
If you are constantly using assert operation for data validation, you should stop.
Why? Assertions can be turned off by simply adding -0 or -00 on the command line:
python filename -O or -OO
Imagine you are building an e-commerce website and assert is used to check if the user is an admin. If assertions are disabled in the Python interpreter then this becomes null-op.
These statements are an essential part of the program which means they must be conditional statements otherwise there will be severe bugs.
The answer to this problem is to never use assert as data validation. Instead, we could do our validation with regular if-statements and raise validation exceptions if necessary, like so:
Assert operations that seem to be important at first sight but aren’t worth writing, like example:
If you take a look at this test case, you’ll see that the assertion always evaluates to True, regardless of the state of the counter variable. This is because it asserts the truth value of a tuples object, rather than the type of the object itself.
Key Takeaways:
Python’s assert statement is a useful tool for testing your code, but developers should only use it to identify bugs.
Asserts can be globally disabled with an interpreter setting to prevent them from being used outside the interpreter’s native code-setters and interpreters.