Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Asserting Conditions

00:00 In the previous lesson, I covered the different ways of using the raise keyword. In this lesson, I’ll show another keyword, assert.

00:08 The assert keyword gets used to test a condition, and if that condition fails, the keyword raises an AssertionError. This is typically done to help with debugging, effectively raising an alarm if some expected condition isn’t true. Like with an exception, you can associate a message with your assertion, and that message gets included in the raised exception.

00:32 You can turn assertions off in your production code to improve performance. There are two ways to do that. You can either provide the -O or --O flags on the command line to the Python interpreter, or you can set the PYTHONOPTIMIZE environment variable to a truthy value.

00:52 Let’s head into the REPL to assert some things. Let me start by asserting something that’s true. Yep. Three is bigger than one, so nothing happens. What about the other way around?

01:09 One is bigger than three. So assert raises an AssertionError. You can also add a message to your assertion.

01:22 One still isn’t bigger than three, and now you’re being told not to be ridiculous as well. One word of caution, assert is a keyword. It isn’t a function, and use of parentheses near it can do something that you might not expect.

01:40 So far so good. That one worked.

01:44 Yep, still fine.

01:49 But what happened there? Because you’re in the REPL, you get a warning. But no, this is just a warning. The assertion passed. That’s because the parentheses is acting as a tuple, and any non-empty tuple is always true.

02:04 You’ve just asserted the tuple, not called a function. Compare the same thing to without the parentheses,

02:15 and that’s what I was trying to do in the first place. I have never liked this fact about assert. It’s a really easy bug to make, which is kind of ironic because assert is supposed to help you find your bugs.

02:27 Back in the olden days, it was even worse because it didn’t use to come with that warning I just showed you. Remember, very important, no parentheses when using assert. And while I’m on my “don’t you do that” soapbox, although an AssertionError is an exception like any other, you should never raise it yourself.

02:47 It will work, but it will confuse anyone else reading your code. If you want to assert something, use the assert keyword. Otherwise, use a different exception for

03:00 your use case.

Become a Member to join the conversation.