DEV Community

Cover image for #Day26 - Assert Statements in Python and When NOT to use them
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

#Day26 - Assert Statements in Python and When NOT to use them

Today we will discuss the assert statement in Python.

Assert statements are a great tool for debugging. Given a boolean condition, they will raise an error if the condition evaluates to False. More specifically, it raises an "AssertionError". We can also include our custom error messages.

General Syntax

# Without Error message
assert boolean Expression

#With Error message
assert boolean Expression, "Error Message"
Enter fullscreen mode Exit fullscreen mode

Standard If.......else

Let's assume we have a function that calculates the Mass of an object. The Mass of an object must always be positive. We can have a check to ensure this

def calculate_mass():
  # Some stuff to calculate the mass
  mass = 10
  if mass > 0:
    pass
  else:
    raise Exception()

calculate_mass()
Enter fullscreen mode Exit fullscreen mode

This would work fine in the above case since mass = 10 and is greater than 0. However, if we set the mass to -10, you'd see the following on the console

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    calculate_mass()
  File "main.py", line 7, in calculate_mass
    raise Exception()
Exception
Enter fullscreen mode Exit fullscreen mode

That's good, we have a check to ensure that the mass is always positive. I

Using Assert

The above check can be done in a single line using an assert statement.

def calculate_mass():
  # Some stuff to calculate the mass
  mass = -10
  assert mass > 0

calculate_mass()
Enter fullscreen mode Exit fullscreen mode

As you can see we needed lesser lines of code and it looks much cleaner. In the above code snippet, since the mass is negative, you'd see the following message on the console

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    calculate_mass()
  File "main.py", line 4, in calculate_mass
    assert mass > 0
AssertionError
Enter fullscreen mode Exit fullscreen mode

So now we have a check to ensure that the mass is always positive. That's good but if a developer were working and got an "AssertionError", how'd they know the reason for the error?

If......Else with error messages

It would be helpful to display a message that an error was raised since the mass was not positive. This would help the future you and other developers debug more efficiently.

def calculate_mass():
  # Some stuff to calculate the mass
  mass = -10
  if mass > 0:
    pass
  else:
    raise Exception("The mass is not positive")

calculate_mass()
Enter fullscreen mode Exit fullscreen mode

If we set the mass to -10 as above, we would get the following message

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    calculate_mass()
  File "main.py", line 7, in calculate_mass
    raise Exception("The mass is not positive")
Exception: The mass is not positive
Enter fullscreen mode Exit fullscreen mode

We can do the above using assert as well and yup it'll still be a single line of code

Custom Error Messages with assert

Let's try to display a custom error message with assert

def calculate_mass():
  # Some stuff to calculate the mass
  mass = -10
  assert mass > 0,"Mass is not positive"

calculate_mass()
Enter fullscreen mode Exit fullscreen mode

Again, this looks much cleaner. The above code would result in the following error

def calculate_mass():
  # Some stuff to calculate the mass
  mass = -10
  assert mass > 0,"Mass is not positive"

calculate_mass()
Enter fullscreen mode Exit fullscreen mode

A couple of Gotchas with assert

Using ( ) in your expression

Consider the following code snippet

assert(10>30 , "Error Message!")
Enter fullscreen mode Exit fullscreen mode

In the above assert statement, since 10 is not greater than 30, an error message should be displayed. However, notice the condition and the error message are inside brackets so essentially they form a non-empty tuple.
A non-empty tuple evaluates to True as a result irrespective of the content inside the tuple, the assert statement will never raise an error. In python 3.8.8, the following error message will be shown in the console if use brackets with assert.

main.py:1: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(10>30 , "Error Message!")
Enter fullscreen mode Exit fullscreen mode

Command Line Flags

assert 10>30, "Error Message!"
print("No Errors")
Enter fullscreen mode Exit fullscreen mode

If you have your code in a file called "main.py", to run the file using the command line, you could type the following command

python main.py
Enter fullscreen mode Exit fullscreen mode

After running the above code, an AssertError would be shown in the console as expected. The print statement will not be executed due to the AssertError

Now, try running one of the following commands

python -O  main.py
python -OO  main.py
Enter fullscreen mode Exit fullscreen mode

If you type one of the above commands and run it, NO Error would be raised and you'd in fact see the output of the print statement.

Screen Shot 2021-04-15 at 11.45.05 PM.png

Passing the "O" flag or the "OO" flag tells Python to ignore the assert statements.

When NOT to use Assert Statements

  • Do not use code that is in production. Anybody can run the python file with the "O" flag and effectively bypass the error checks
  • Do not use assert statements instead of other Exceptions/Errors such as Value Error, Key Error etc. Read about more errors here

Top comments (0)