Using the assert Keyword
The way that it operates is that you want to assert that a certain condition is met—the one that follows the
assert keyword—and then if it is true, your code will continue. If it’s wrong, then an assertion exception is going to be raised.
Let’s look at it in some code. Like I mentioned, there’s an assertion exception,
AssertionError, that is built-in in Python as well. It’s one of those many built-in errors, so you could raise it just like you did before with your custom error.
So I’m going to say
python main.py, and you see, again, Python raises the
AssertionError, and it also has the message that you passed over here. Now, why is this different, a little bit, than the more explicit way that you wrote it before? And that’s about how
assert is implemented in Python.
if not a: raise
b. This is what you have here.
if not sys.platform.startswith("linux"): raise
AssertionError with a message. So this is the same, right? But then you also have this
if __debug__. And this is not a problem if you run Python without any optimizations, but there’s ways to run your Python code with some optimizations enabled, which cuts out things like docstrings.
So you should only use
assert if it’s not critical for your program to run because you might want to eventually optimize the code when you’re running it in production, and then anything that uses the
assert keyword is just going to be completely skipped. So if it’s critical to the functioning of your program, then don’t use
assert but be more explicit and actually write out your exceptions.
Since in the code that you’re writing here, the check for which platform is it running on seems pretty critical for the code, I would advise against using the
assert keyword in here and just stick with being more explicit.
So, this is what the
assert keyword is for. As a debugging tool, you want to use it to throw in some quick checks for you as a developer to figure out whether some conditions are met, and stop execution if the conditions aren’t met. You don’t want to use it in production code, especially in code that you would want to optimize because if you run Python with optimizations, then your asserts that you write using the
assert keyword are just going to be skipped completely. So, that’s something that’s good to know.
Become a Member to join the conversation.