Things You Didn’t Know About Python Assertion

Varun Singh
4 min readJan 23, 2022

--

Things You Didn’t Know About Python Assertion
Created in Canva | Edited by Varun Singh

Python’s assert statement provides us with ways to debug and test any condition in our code. If the assert condition evaluates to true, nothing happens, and your code continues to execute the rest of your lines of code. But if the condition fails to evaluate to true, an AssertionError exception is raised.

If you are someone, who is fairly new to Python assert statement and how it is actually, here is an example for you —

def create_product(product, price):    # price should be greater than 0
assert 0< price

# code to create a product in database

return price

Did you notice the assert statement in there? This statement will make sure that, the product that will be created should not have price equal or less than 0(Zero).

Now, let’s try to create a valid product —

>>> product1 = {"title": "Watch"}
>>> price = 1200
>>> create_product(product1, price)

If you would create the above product, the assert statement will resolve to true. Alright, this worked nicely. Now, let’s try to create an invalid product with price equal to 0(Zero) —

>>> product1 = {"title": "Juicer"}
>>> price = 0
>>> create_product(product1, price)
Traceback (most recent call last):
File "<input>", line 1,in <module>
create_product(prod, 2.0)
File "<input>", line 4,increate_product
assert 0< price
**AssertionError**

As you can see, when we try to apply this invalid discount, our program halts with an AssertionError.

You can also see how the exception stack trace points out the exact line of code containing the failed assertion. This speeds up debugging efforts considerably, and it will make your programs more maintainable in the long run. And that, my friend, is the power of assertions.

Why Not Use Conditionals? If and Else

If you are wondering, why I did not use conditional statements and raise an exception based on the result of a condition — The true purpose of an assert statement is to inform a developer about un-recoverable errors.

These errors are not always expected to occur like — FileNotFoundException, etc. Assertions are self-checks for our program to halt at a position if it is not recoverable from thereafter.

For now, keep in mind that Python’s assert statement is a debugging aid, not a mechanism for handling run-time errors.

The debug Global Variable

Many of you must be wondering, why this article is stating that the assert guy is only used for debugging python code. Why the specific use of the word Debug? Let’s check the assert statement syntax and try to understand this better —

assertiion_statement ::="assert" expression1 ["," expression2]

As shown above, expression1 is the condition we test, and the optional expression2 is an error message that’s displayed if the assertion fails. Now, when such assert statements gets executed, the Python interpreter transforms it to something like shown below —

if__debug__:
if notexpression1:
**raiseAssertionError**(expression2)

Wow, where does this scary debug come from? Before the assertion statement even gets executed, there is an additional check for the global debug variable. This is an in-built flag, that’s usually true but if optimizations are enabled this flag will be false.

Hence, I have mentioned that assert is something that a programmer can use for debugging and testing(which is usually the case).

Never Use Assertions for Data Validations

Are you thinking or have planned to use assertions for data validations? Well, that would not be such a good idea.

The biggest problem with using asserts in Python is that assertions can be globally disabled with the -O and -OO command-line switches, as well as the PYTHONOPTIMIZE environment variable in CPython.

This turns any assert statement into a null operation, which means, the assertions simply get compiled away and won’t be evaluated. Hence, your data validations will pass even if they were not supposed to.

def delete_product(product_id, user):
assertuser.is_admin(), 'Must be admin'
# your logic to delete the product from database here
...

Take a close look at this delete_product function. Now, what’s going to happen if assertions are disabled? I hope you already know now that we have learned, Assertions can be disabled. Hence the product will be deleted if assertions are disabled without the assert statement in our code being evaluated to anything.

That’s scary right. So, I advise you not to use assertions for data validations.

More About The Author😄

I am a full-time software engineer with 4+ years of experience in Python, AWS, and many more technologies. I have started writing recently as it helps me to read more. I am looking forward to sharing technical knowledge and my life experiences with people out there.

Register Here for my Programmer Weekly newsletter where I share interesting tutorials, python libraries, and tools, etc.

Github | LinkedIn | Twitter | Facebook | Quora | Programmer Weekly

--

--

Varun Singh

Data Analyst turned Software Developer and Blogger. Enjoys a hot cup of tea and nature’s spell.