Python Assert Statement — Everything You Need To Know Explained in 5 Minutes | by Dario Radečić | Towards Data Science

Being an interpreted and dynamically-typed language, Python has a bad reputation for unexpected and hard-to-track bugs. The assert statement could save you a nerve or two. It’s a go-to way of catching things that shouldn’t happen early on, most likely at the beginning of a function.
It’s a simple boolean expression that checks if a condition returns true. If so, nothing happens. If not, the script raises an AssertionError with an optional message.
Keep in mind — assertion is not a replacement for exception handling. You should use try except blocks for any error that’s bound to happen at some point. Use assertion for ones that shouldn’t happen.
Don’t feel like reading? Check out my video on the topic:
As you would imagine, the assert keyword is built into Python. It must be followed by a condition, and you can optionally put a message that gets printed if the condition evaluates to false.
Here’s the syntax:
assert <condition>, <optional error message>
So for example, Megan can’t enter the club if she’s underage:
assert age > 18, 'Go home, Megan.'
Let’s leave Megan alone for now and focus on an even simpler example. We have a variable x which is set to 1. Let’s assert it and see what happens:
x = 1assert x == 1
Here’s the output:
Literally nothing happens. That’s because the condition evaluated to true, so no error was raised. Let’s change the code slightly:
x = 1assert x == 2
The output is different this time:
You’ve got an AssertionError because the condition evaluated to false — x is 1, so it can’t be 2. The console output provided no explanation, which probably isn’t what you want. You can specify the error message that gets printed if AssertionError is raised:
x = 1assert x == 2, 'X should be 1'
Here’s the output:
Easy, right? It should be. In reality, you’re far more likely to write assert statements at the beginning of a function. Let’s see how to do that next.
Let’s declare a simple Python function. It will take in a list as an argument, sum it, and then return the sum as a float. There are two problems you want to catch early on:
Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints.Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want.
Is the list passed to the function? You can use type hints in Python to indicate which data type should be passed, but no one’s stopping you to pass a dictionary instead of a list. Hints are just that — hints.
Is the list empty? You can’t sum an empty list, obviously. Well, calling sum([]) returns 0, but that’s not what you want.
That’s why you’ll have two assertion statements, followed by a piece of code for summing up list elements. Python interpreter won’t get to that code if both conditions don’t evaluate to true:
def sum_list(lst: list) -> float:    assert type(lst) == list, 'Param `lst` must be of type list!'    assert len(lst), 'The input list is empty!'    total = 0    for item in lst:        total += item         return total
Let’s now try to call sum_list() and pass in a dictionary:
lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum)
Here’s what happens:
Just what you wanted — a list wasn’t provided to the function, so an appropriate assertion error was printed to the console.
What if you pass an empty list?
lst_sum = sum_list(lst=[])print(lst_sum)
You still get the AssertionError, but this time with a different message.
And finally, let’s verify the function works correctly by providing a list of numbers:
lst_sum = sum_list([1.11, 2.21, 3.14])print(lst_sum)
And there you have it, works as advertised.
What’s particularly neat about assert statements is that you can ignore them when running the scripts, without modifying the code.
Here’s how you’d run a Python script normally:
python3 script.py
If you have asserts statements and want to ignore them, simply add the -O to the command:
python3 -O script.py
Here’s an example of our assertion.py file with the following code inside (you’ve declared the sum_list() function earlier):
lst_sum = sum_list(lst={'a': 1, 'b': 4})print(lst_sum)
As you can see, the TypeError was raised because the dictionary was passed instead of a list.
I’ve told it before, but I’ll repeat once again — assertion isn’t a replacement for try except blocks. You should always use try except for errors that will inevitably happen.
Still, assert statements have at least two things going for them.
assert is more compact and readable than if. It’s easier to write assert <condition>, <message> than if <condition>: <message>. At least it will save you a line of code. Also, by writing assert you know you’re checking for cases that shouldn’t happen. if is just a generic check.
assert statements can be ignored at runtime. You’ve already seen how to do this, so I won’t repeat myself.
To summarize, assert is faster to write and easier to distinguish from your regular condition checks. Use them well, but never as the only approach to exception handling.
What do you guys think of assert statements? Are they a part of your Python projects, or do you get around with if’s and try except?. Please let me know in the comment section below.
Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
medium.com
Sign up for my newsletter
Subscribe on YouTube
Connect on LinkedIn